@promptbook/node 0.71.0-0 → 0.72.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 +6 -5
  2. package/esm/index.es.js +1312 -2132
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +5 -11
  5. package/esm/typings/src/_packages/openai.index.d.ts +4 -0
  6. package/esm/typings/src/_packages/types.index.d.ts +2 -12
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +2 -3
  9. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -1
  10. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +1 -16
  11. package/esm/typings/src/config.d.ts +1 -14
  12. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +0 -3
  13. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +1 -2
  14. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +0 -5
  15. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +8 -9
  16. package/esm/typings/src/execution/createPipelineExecutor.d.ts +72 -0
  17. package/esm/typings/src/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +1 -1
  18. package/esm/typings/src/execution/utils/addUsage.d.ts +0 -56
  19. package/esm/typings/src/execution/utils/checkExpectations.d.ts +0 -2
  20. package/esm/typings/src/execution/utils/usage-constants.d.ts +127 -0
  21. package/esm/typings/src/execution/utils/usageToHuman.d.ts +4 -3
  22. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +15 -14
  23. package/esm/typings/src/formats/csv/{CsvFormatDefinition.d.ts → ListFormatDefinition.d.ts} +3 -6
  24. package/esm/typings/src/formats/index.d.ts +1 -1
  25. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +3 -4
  26. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +16 -0
  27. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +3 -4
  28. package/esm/typings/src/knowledge/dialogs/callback/CallbackInterfaceTools.d.ts +1 -1
  29. package/esm/typings/src/knowledge/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +1 -1
  30. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +3 -2
  31. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +3 -2
  32. package/esm/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -1
  33. package/esm/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +1 -1
  34. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +37 -0
  35. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionToolsOptions.d.ts +14 -0
  36. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +3 -2
  37. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +1 -1
  38. package/esm/typings/src/scripting/javascript/JavascriptEvalExecutionTools.d.ts +1 -1
  39. package/esm/typings/src/scripting/python/PythonExecutionTools.d.ts +1 -1
  40. package/esm/typings/src/scripting/typescript/TypescriptExecutionTools.d.ts +1 -1
  41. package/esm/typings/src/storage/files-storage/FilesStorage.d.ts +1 -1
  42. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +2 -9
  43. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +0 -1
  44. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +0 -5
  45. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +0 -3
  46. package/esm/typings/src/utils/expectation-counters/index.d.ts +0 -3
  47. package/esm/typings/src/utils/{parameters/extractParameterNames.d.ts → extractParameterNames.d.ts} +2 -2
  48. package/esm/typings/src/utils/organization/{empty_object.d.ts → f.d.ts} +1 -5
  49. package/esm/typings/src/utils/{parameters/replaceParameters.d.ts → replaceParameters.d.ts} +2 -2
  50. package/package.json +13 -18
  51. package/umd/index.umd.js +1316 -2135
  52. package/umd/index.umd.js.map +1 -1
  53. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +0 -23
  54. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +0 -45
  55. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +0 -20
  56. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +0 -40
  57. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +0 -10
  58. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +0 -55
  59. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +0 -62
  60. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +0 -19
  61. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +0 -74
  62. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +0 -34
  63. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +0 -10
  64. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +0 -27
  65. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +0 -30
  66. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +0 -10
  67. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +0 -30
  68. package/esm/typings/src/formats/csv/CsvSettings.d.ts +0 -13
  69. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +0 -19
  70. package/esm/typings/src/utils/organization/just_empty_object.d.ts +0 -12
  71. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +0 -27
  72. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +0 -10
  73. package/esm/typings/src/utils/validators/parameterName/validateParameterName.test.d.ts +0 -1
  74. /package/esm/typings/src/{utils/parameters/extractParameterNames.test.d.ts → execution/utils/usageToHuman.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{parameters/mapAvailableToExpectedParameters.test.d.ts → extractParameterNames.test.d.ts} +0 -0
  76. /package/esm/typings/src/utils/{parameters/replaceParameters.test.d.ts → replaceParameters.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('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
- })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, posix, dotenv) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.hexEncoder, global.sha256, global.posix, global.dotenv));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, hexEncoder, sha256, posix, dotenv) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -35,7 +35,7 @@
35
35
  /**
36
36
  * The version of the Promptbook library
37
37
  */
38
- var PROMPTBOOK_VERSION = '0.70.0-1';
38
+ var PROMPTBOOK_VERSION = '0.68.5';
39
39
  // TODO:[main] !!!! List here all the versions and annotate + put into script
40
40
 
41
41
  /*! *****************************************************************************
@@ -388,13 +388,13 @@
388
388
  *
389
389
  * @public exported from `@promptbook/core`
390
390
  */
391
- var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
391
+ var MAX_PARALLEL_COUNT = 5;
392
392
  /**
393
393
  * The maximum number of attempts to execute LLM task before giving up
394
394
  *
395
395
  * @public exported from `@promptbook/core`
396
396
  */
397
- var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
397
+ var MAX_EXECUTION_ATTEMPTS = 3;
398
398
  /**
399
399
  * The maximum length of the (generated) filename
400
400
  *
@@ -425,7 +425,6 @@
425
425
  'samples',
426
426
  'modelName',
427
427
  'currentDate',
428
- // <- TODO: !!!!! list here all command names
429
428
  // <- TODO: Add more like 'date', 'modelName',...
430
429
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
431
430
  ]);
@@ -442,32 +441,12 @@
442
441
  */
443
442
  var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
444
443
  // <- TODO: [🧜‍♂️]
445
- /**
446
- * @@@
447
- *
448
- * @public exported from `@promptbook/core`
449
- */
450
- var DEFAULT_CSV_SETTINGS = Object.freeze({
451
- delimiter: ',',
452
- quoteChar: '"',
453
- newline: '\n',
454
- skipEmptyLines: true,
455
- });
456
444
  /**
457
445
  * @@@
458
446
  *
459
447
  * @public exported from `@promptbook/core`
460
448
  */
461
449
  var IS_VERBOSE = false;
462
- /**
463
- * @@@
464
- *
465
- * @private within the repository
466
- */
467
- var IS_PIPELINE_LOGIC_VALIDATED = just(
468
- /**/
469
- // Note: In normal situations, we check the pipeline logic:
470
- true);
471
450
  /**
472
451
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
473
452
  */
@@ -720,127 +699,6 @@
720
699
  * TODO: [🧠] Should be in generated .ptbk.md file GENERATOR_WARNING
721
700
  */
722
701
 
723
- /**
724
- * @@@
725
- *
726
- * @public exported from `@promptbook/utils`
727
- */
728
- function deepClone(objectValue) {
729
- return JSON.parse(JSON.stringify(objectValue));
730
- /*
731
- TODO: [🧠] Is there a better implementation?
732
- > const propertyNames = Object.getOwnPropertyNames(objectValue);
733
- > for (const propertyName of propertyNames) {
734
- > const value = (objectValue as really_any)[propertyName];
735
- > if (value && typeof value === 'object') {
736
- > deepClone(value);
737
- > }
738
- > }
739
- > return Object.assign({}, objectValue);
740
- */
741
- }
742
- /**
743
- * TODO: [🧠] Is there a way how to meaningfully test this utility
744
- */
745
-
746
- /**
747
- * @@@
748
- *
749
- * @public exported from `@promptbook/core`
750
- */
751
- var ZERO_USAGE = $deepFreeze({
752
- price: { value: 0 },
753
- input: {
754
- tokensCount: { value: 0 },
755
- charactersCount: { value: 0 },
756
- wordsCount: { value: 0 },
757
- sentencesCount: { value: 0 },
758
- linesCount: { value: 0 },
759
- paragraphsCount: { value: 0 },
760
- pagesCount: { value: 0 },
761
- },
762
- output: {
763
- tokensCount: { value: 0 },
764
- charactersCount: { value: 0 },
765
- wordsCount: { value: 0 },
766
- sentencesCount: { value: 0 },
767
- linesCount: { value: 0 },
768
- paragraphsCount: { value: 0 },
769
- pagesCount: { value: 0 },
770
- },
771
- });
772
- /**
773
- * Function `addUsage` will add multiple usages into one
774
- *
775
- * Note: If you provide 0 values, it returns ZERO_USAGE
776
- *
777
- * @public exported from `@promptbook/core`
778
- */
779
- function addUsage() {
780
- var usageItems = [];
781
- for (var _i = 0; _i < arguments.length; _i++) {
782
- usageItems[_i] = arguments[_i];
783
- }
784
- return usageItems.reduce(function (acc, item) {
785
- var e_1, _a, e_2, _b;
786
- var _c;
787
- acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
788
- try {
789
- for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
790
- var key = _e.value;
791
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
792
- //@ts-ignore
793
- if (item.input[key]) {
794
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
795
- //@ts-ignore
796
- acc.input[key].value += item.input[key].value || 0;
797
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
798
- //@ts-ignore
799
- if (item.input[key].isUncertain) {
800
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
801
- //@ts-ignore
802
- acc.input[key].isUncertain = true;
803
- }
804
- }
805
- }
806
- }
807
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
808
- finally {
809
- try {
810
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
811
- }
812
- finally { if (e_1) throw e_1.error; }
813
- }
814
- try {
815
- for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
816
- var key = _g.value;
817
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
818
- //@ts-ignore
819
- if (item.output[key]) {
820
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
821
- //@ts-ignore
822
- acc.output[key].value += item.output[key].value || 0;
823
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
824
- //@ts-ignore
825
- if (item.output[key].isUncertain) {
826
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
827
- //@ts-ignore
828
- acc.output[key].isUncertain = true;
829
- }
830
- }
831
- }
832
- }
833
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
834
- finally {
835
- try {
836
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
837
- }
838
- finally { if (e_2) throw e_2.error; }
839
- }
840
- return acc;
841
- }, deepClone(ZERO_USAGE));
842
- }
843
-
844
702
  /**
845
703
  * Async version of Array.forEach
846
704
  *
@@ -916,6 +774,59 @@
916
774
  });
917
775
  }
918
776
 
777
+ /**
778
+ * Represents the usage with no resources consumed
779
+ *
780
+ * @public exported from `@promptbook/core`
781
+ */
782
+ var ZERO_USAGE = $deepFreeze({
783
+ price: { value: 0 },
784
+ input: {
785
+ tokensCount: { value: 0 },
786
+ charactersCount: { value: 0 },
787
+ wordsCount: { value: 0 },
788
+ sentencesCount: { value: 0 },
789
+ linesCount: { value: 0 },
790
+ paragraphsCount: { value: 0 },
791
+ pagesCount: { value: 0 },
792
+ },
793
+ output: {
794
+ tokensCount: { value: 0 },
795
+ charactersCount: { value: 0 },
796
+ wordsCount: { value: 0 },
797
+ sentencesCount: { value: 0 },
798
+ linesCount: { value: 0 },
799
+ paragraphsCount: { value: 0 },
800
+ pagesCount: { value: 0 },
801
+ },
802
+ });
803
+ /**
804
+ * Represents the usage with unknown resources consumed
805
+ *
806
+ * @public exported from `@promptbook/core`
807
+ */
808
+ $deepFreeze({
809
+ price: { value: 0, isUncertain: true },
810
+ input: {
811
+ tokensCount: { value: 0, isUncertain: true },
812
+ charactersCount: { value: 0, isUncertain: true },
813
+ wordsCount: { value: 0, isUncertain: true },
814
+ sentencesCount: { value: 0, isUncertain: true },
815
+ linesCount: { value: 0, isUncertain: true },
816
+ paragraphsCount: { value: 0, isUncertain: true },
817
+ pagesCount: { value: 0, isUncertain: true },
818
+ },
819
+ output: {
820
+ tokensCount: { value: 0, isUncertain: true },
821
+ charactersCount: { value: 0, isUncertain: true },
822
+ wordsCount: { value: 0, isUncertain: true },
823
+ sentencesCount: { value: 0, isUncertain: true },
824
+ linesCount: { value: 0, isUncertain: true },
825
+ paragraphsCount: { value: 0, isUncertain: true },
826
+ pagesCount: { value: 0, isUncertain: true },
827
+ },
828
+ });
829
+
919
830
  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"}];
920
831
 
921
832
  /**
@@ -1123,26 +1034,6 @@
1123
1034
  * @public exported from `@promptbook/core`
1124
1035
  */
1125
1036
  function validatePipeline(pipeline) {
1126
- if (IS_PIPELINE_LOGIC_VALIDATED) {
1127
- validatePipelineCore(pipeline);
1128
- }
1129
- else {
1130
- try {
1131
- validatePipelineCore(pipeline);
1132
- }
1133
- catch (error) {
1134
- if (!(error instanceof PipelineLogicError)) {
1135
- throw error;
1136
- }
1137
- 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 "); }));
1138
- }
1139
- }
1140
- return pipeline;
1141
- }
1142
- /**
1143
- * @private internal function for `validatePipeline`
1144
- */
1145
- function validatePipelineCore(pipeline) {
1146
1037
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1147
1038
  var e_1, _a, e_2, _b, e_3, _c;
1148
1039
  var pipelineIdentification = (function () {
@@ -1167,12 +1058,12 @@
1167
1058
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1168
1059
  if (!Array.isArray(pipeline.parameters)) {
1169
1060
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1170
- 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 "); }));
1061
+ 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 "); }));
1171
1062
  }
1172
1063
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1173
1064
  if (!Array.isArray(pipeline.templates)) {
1174
1065
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1175
- 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 "); }));
1066
+ 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 "); }));
1176
1067
  }
1177
1068
  var _loop_1 = function (parameter) {
1178
1069
  if (parameter.isInput && parameter.isOutput) {
@@ -1341,9 +1232,9 @@
1341
1232
  while (unresovedTemplates.length > 0) {
1342
1233
  _loop_3();
1343
1234
  }
1235
+ return pipeline;
1344
1236
  }
1345
1237
  /**
1346
- * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1347
1238
  * TODO: [🧠] Work with promptbookVersion
1348
1239
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1349
1240
  * > /**
@@ -2081,54 +1972,153 @@
2081
1972
  */
2082
1973
 
2083
1974
  /**
2084
- * Determine if the pipeline is fully prepared
1975
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2085
1976
  *
2086
- * @public exported from `@promptbook/core`
1977
+ * @param script from which to extract the variables
1978
+ * @returns the list of variable names
1979
+ * @throws {ParseError} if the script is invalid
1980
+ * @public exported from `@promptbook/utils`
2087
1981
  */
2088
- function isPipelinePrepared(pipeline) {
2089
- // Note: Ignoring `pipeline.preparations` @@@
2090
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2091
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2092
- return false;
1982
+ function extractVariables(script) {
1983
+ var variables = new Set();
1984
+ script = "(()=>{".concat(script, "})()");
1985
+ try {
1986
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1987
+ try {
1988
+ eval(script);
1989
+ }
1990
+ catch (error) {
1991
+ if (!(error instanceof ReferenceError)) {
1992
+ throw error;
1993
+ }
1994
+ var undefinedName = error.message.split(' ')[0];
1995
+ /*
1996
+ Note: Parsing the error
1997
+ [PipelineUrlError: thing is not defined]
1998
+ */
1999
+ if (!undefinedName) {
2000
+ throw error;
2001
+ }
2002
+ if (script.includes(undefinedName + '(')) {
2003
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2004
+ }
2005
+ else {
2006
+ variables.add(undefinedName);
2007
+ script = "const ".concat(undefinedName, " = '';") + script;
2008
+ }
2009
+ }
2093
2010
  }
2094
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2095
- return false;
2011
+ catch (error) {
2012
+ if (!(error instanceof Error)) {
2013
+ throw error;
2014
+ }
2015
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2096
2016
  }
2097
- /*
2098
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2099
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2100
- > return false;
2101
- > }
2102
- */
2103
- return true;
2017
+ return variables;
2104
2018
  }
2105
2019
  /**
2106
- * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2107
- * TODO: [🐠] Maybe base this on `makeValidator`
2108
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2109
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2110
- * - [🏍] ? Is context in each template
2111
- * - [♨] Are samples prepared
2112
- * - [♨] Are templates prepared
2020
+ * TODO: [🔣] Support for multiple languages - python, java,...
2113
2021
  */
2114
2022
 
2115
2023
  /**
2116
- * Serializes an error into a [🚉] JSON-serializable object
2024
+ * Parses the template and returns the set of all used parameters
2117
2025
  *
2026
+ * @param template the template with used parameters
2027
+ * @returns the set of parameter names
2028
+ * @throws {ParseError} if the script is invalid
2118
2029
  * @public exported from `@promptbook/utils`
2119
2030
  */
2120
- function serializeError(error) {
2121
- var name = error.name, message = error.message, stack = error.stack;
2122
- if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2123
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2124
- }
2125
- return {
2126
- name: name,
2031
+ function extractParameterNamesFromTemplate(template) {
2032
+ var e_1, _a, e_2, _b, e_3, _c;
2033
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2034
+ var parameterNames = new Set();
2035
+ try {
2036
+ 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()) {
2037
+ var parameterName = _e.value;
2038
+ parameterNames.add(parameterName);
2039
+ }
2040
+ }
2041
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2042
+ finally {
2043
+ try {
2044
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2045
+ }
2046
+ finally { if (e_1) throw e_1.error; }
2047
+ }
2048
+ if (templateType === 'SCRIPT_TEMPLATE') {
2049
+ try {
2050
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2051
+ var parameterName = _g.value;
2052
+ parameterNames.add(parameterName);
2053
+ }
2054
+ }
2055
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2056
+ finally {
2057
+ try {
2058
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2059
+ }
2060
+ finally { if (e_2) throw e_2.error; }
2061
+ }
2062
+ }
2063
+ try {
2064
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2065
+ var jokerName = _j.value;
2066
+ parameterNames.add(jokerName);
2067
+ }
2068
+ }
2069
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2070
+ finally {
2071
+ try {
2072
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2073
+ }
2074
+ finally { if (e_3) throw e_3.error; }
2075
+ }
2076
+ parameterNames.delete('content');
2077
+ // <- Note {websiteContent} is used in `preparedContent`
2078
+ return parameterNames;
2079
+ }
2080
+ /**
2081
+ * TODO: [🔣] If script require contentLanguage
2082
+ */
2083
+
2084
+ /**
2085
+ * Serializes an error into a [🚉] JSON-serializable object
2086
+ *
2087
+ * @public exported from `@promptbook/utils`
2088
+ */
2089
+ function serializeError(error) {
2090
+ var name = error.name, message = error.message, stack = error.stack;
2091
+ if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2092
+ throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2093
+ }
2094
+ return {
2095
+ name: name,
2127
2096
  message: message,
2128
2097
  stack: stack,
2129
2098
  };
2130
2099
  }
2131
2100
 
2101
+ /**
2102
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2103
+ *
2104
+ * @public exported from `@promptbook/utils`
2105
+ */
2106
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2107
+ try {
2108
+ JSON.parse(value);
2109
+ return true;
2110
+ }
2111
+ catch (error) {
2112
+ if (!(error instanceof Error)) {
2113
+ throw error;
2114
+ }
2115
+ if (error.message.includes('Unexpected token')) {
2116
+ return false;
2117
+ }
2118
+ return false;
2119
+ }
2120
+ }
2121
+
2132
2122
  /**
2133
2123
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2134
2124
  *
@@ -2155,10 +2145,9 @@
2155
2145
  });
2156
2146
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2157
2147
  get: function () {
2158
- return this.llmExecutionTools.map(function (_a, index) {
2159
- var title = _a.title;
2160
- return "".concat(index + 1, ") `").concat(title, "`");
2161
- }).join('\n');
2148
+ return this.llmExecutionTools
2149
+ .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2150
+ .join('\n');
2162
2151
  },
2163
2152
  enumerable: false,
2164
2153
  configurable: true
@@ -2356,7 +2345,9 @@
2356
2345
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2357
2346
  }
2358
2347
  else {
2359
- 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 "); }));
2348
+ 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
2349
+ .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2350
+ .join('\n')), "\n\n "); }));
2360
2351
  }
2361
2352
  }
2362
2353
  });
@@ -2422,171 +2413,306 @@
2422
2413
  */
2423
2414
 
2424
2415
  /**
2425
- * Takes an item or an array of items and returns an array of items
2426
- *
2427
- * 1) Any item except array and undefined returns array with that one item (also null)
2428
- * 2) Undefined returns empty array
2429
- * 3) Array returns itself
2416
+ * Extracts all code blocks from markdown.
2430
2417
  *
2431
- * @private internal utility
2432
- */
2433
- function arrayableToArray(input) {
2434
- if (input === undefined) {
2435
- return [];
2436
- }
2437
- if (input instanceof Array) {
2438
- return input;
2439
- }
2440
- return [input];
2441
- }
2442
-
2443
- /**
2444
- * Parses the given script and returns the list of all used variables that are not defined in the script
2418
+ * Note: There are multiple simmilar function:
2419
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2420
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2421
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2422
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2445
2423
  *
2446
- * @param script from which to extract the variables
2447
- * @returns the list of variable names
2448
- * @throws {ParseError} if the script is invalid
2449
- * @public exported from `@promptbook/utils`
2424
+ * @param markdown any valid markdown
2425
+ * @returns code blocks with language and content
2426
+ * @throws {ParseError} if block is not closed properly
2427
+ * @public exported from `@promptbook/markdown-utils`
2450
2428
  */
2451
- function extractVariables(script) {
2452
- var variables = new Set();
2453
- script = "(()=>{".concat(script, "})()");
2429
+ function extractAllBlocksFromMarkdown(markdown) {
2430
+ var e_1, _a;
2431
+ var codeBlocks = [];
2432
+ var lines = markdown.split('\n');
2433
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2434
+ lines.push('');
2435
+ var currentCodeBlock = null;
2454
2436
  try {
2455
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2456
- try {
2457
- eval(script);
2458
- }
2459
- catch (error) {
2460
- if (!(error instanceof ReferenceError)) {
2461
- throw error;
2462
- }
2463
- var undefinedName = error.message.split(' ')[0];
2464
- /*
2465
- Note: Parsing the error
2466
- [PipelineUrlError: thing is not defined]
2467
- */
2468
- if (!undefinedName) {
2469
- throw error;
2437
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2438
+ var line = lines_1_1.value;
2439
+ if (line.startsWith('> ') || line === '>') {
2440
+ if (currentCodeBlock === null) {
2441
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2442
+ } /* not else */
2443
+ if (currentCodeBlock.blockNotation === '>') {
2444
+ if (currentCodeBlock.content !== '') {
2445
+ currentCodeBlock.content += '\n';
2446
+ }
2447
+ currentCodeBlock.content += line.slice(2);
2470
2448
  }
2471
- if (script.includes(undefinedName + '(')) {
2472
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2449
+ }
2450
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2451
+ codeBlocks.push(currentCodeBlock);
2452
+ currentCodeBlock = null;
2453
+ }
2454
+ /* not else */
2455
+ if (line.startsWith('```')) {
2456
+ var language = line.slice(3).trim() || null;
2457
+ if (currentCodeBlock === null) {
2458
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2473
2459
  }
2474
2460
  else {
2475
- variables.add(undefinedName);
2476
- script = "const ".concat(undefinedName, " = '';") + script;
2461
+ if (language !== null) {
2462
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2463
+ }
2464
+ codeBlocks.push(currentCodeBlock);
2465
+ currentCodeBlock = null;
2477
2466
  }
2478
2467
  }
2479
- }
2480
- catch (error) {
2481
- if (!(error instanceof Error)) {
2482
- throw error;
2483
- }
2484
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2485
- }
2486
- return variables;
2487
- }
2488
- /**
2489
- * TODO: [🔣] Support for multiple languages - python, java,...
2490
- */
2491
-
2492
- /**
2493
- * Parses the template and returns the set of all used parameters
2494
- *
2495
- * @param template the template with used parameters
2496
- * @returns the set of parameter names
2497
- * @throws {ParseError} if the script is invalid
2498
- * @public exported from `@promptbook/utils`
2499
- */
2500
- function extractParameterNamesFromTemplate(template) {
2501
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2502
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2503
- var parameterNames = new Set();
2504
- try {
2505
- 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()) {
2506
- var parameterName = _f.value;
2507
- parameterNames.add(parameterName);
2468
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2469
+ if (currentCodeBlock.content !== '') {
2470
+ currentCodeBlock.content += '\n';
2471
+ }
2472
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2473
+ }
2508
2474
  }
2509
2475
  }
2510
2476
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2511
2477
  finally {
2512
2478
  try {
2513
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2479
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2514
2480
  }
2515
2481
  finally { if (e_1) throw e_1.error; }
2516
2482
  }
2517
- if (templateType === 'SCRIPT_TEMPLATE') {
2518
- try {
2519
- for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2520
- var parameterName = _h.value;
2521
- parameterNames.add(parameterName);
2522
- }
2523
- }
2524
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2525
- finally {
2526
- try {
2527
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2528
- }
2529
- finally { if (e_2) throw e_2.error; }
2530
- }
2531
- }
2532
- try {
2533
- for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2534
- var jokerName = _k.value;
2535
- parameterNames.add(jokerName);
2536
- }
2537
- }
2538
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2539
- finally {
2540
- try {
2541
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2542
- }
2543
- finally { if (e_3) throw e_3.error; }
2544
- }
2545
- parameterNames.delete('content');
2546
- // <- Note {websiteContent} is used in `preparedContent`
2547
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2548
- if (foreach !== undefined) {
2549
- try {
2550
- for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2551
- var subparameterName = _m.value;
2552
- if (parameterNames.has(subparameterName)) {
2553
- parameterNames.delete(subparameterName);
2554
- parameterNames.add(foreach.parameterName);
2555
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2556
- }
2557
- }
2558
- }
2559
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
2560
- finally {
2561
- try {
2562
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2563
- }
2564
- finally { if (e_4) throw e_4.error; }
2565
- }
2483
+ if (currentCodeBlock !== null) {
2484
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2566
2485
  }
2567
- return parameterNames;
2486
+ return codeBlocks;
2568
2487
  }
2569
2488
  /**
2570
- * TODO: [🔣] If script require contentLanguage
2489
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2571
2490
  */
2572
2491
 
2573
2492
  /**
2574
- * Create difference set of two sets.
2493
+ * Extracts extracts exactly one valid JSON code block
2575
2494
  *
2576
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2577
- * @public exported from `@promptbook/utils`
2578
- */
2579
- function difference(a, b, isEqual) {
2580
- var e_1, _a;
2581
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2582
- var diff = new Set();
2583
- var _loop_1 = function (itemA) {
2584
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2585
- diff.add(itemA);
2586
- }
2587
- };
2588
- try {
2589
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2495
+ * - When given string is a valid JSON as it is, it just returns it
2496
+ * - When there is no JSON code block the function throws a `ParseError`
2497
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
2498
+ *
2499
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2500
+ * Note: There are multiple simmilar function:
2501
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2502
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2503
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2504
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2505
+ *
2506
+ * @public exported from `@promptbook/markdown-utils`
2507
+ * @throws {ParseError} if there is no valid JSON block in the markdown
2508
+ */
2509
+ function extractJsonBlock(markdown) {
2510
+ if (isValidJsonString(markdown)) {
2511
+ return markdown;
2512
+ }
2513
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2514
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2515
+ var content = _a.content;
2516
+ return isValidJsonString(content);
2517
+ });
2518
+ if (jsonBlocks.length === 0) {
2519
+ throw new Error('There is no valid JSON block in the markdown');
2520
+ }
2521
+ if (jsonBlocks.length > 1) {
2522
+ throw new Error('There are multiple JSON code blocks in the markdown');
2523
+ }
2524
+ return jsonBlocks[0].content;
2525
+ }
2526
+ /**
2527
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2528
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2529
+ */
2530
+
2531
+ /**
2532
+ * Determine if the pipeline is fully prepared
2533
+ *
2534
+ * @public exported from `@promptbook/core`
2535
+ */
2536
+ function isPipelinePrepared(pipeline) {
2537
+ // Note: Ignoring `pipeline.preparations` @@@
2538
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2539
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2540
+ return false;
2541
+ }
2542
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2543
+ return false;
2544
+ }
2545
+ /*
2546
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2547
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2548
+ > return false;
2549
+ > }
2550
+ */
2551
+ return true;
2552
+ }
2553
+ /**
2554
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2555
+ * TODO: [🐠] Maybe base this on `makeValidator`
2556
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2557
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2558
+ * - [🏍] ? Is context in each template
2559
+ * - [♨] Are samples prepared
2560
+ * - [♨] Are templates prepared
2561
+ */
2562
+
2563
+ /**
2564
+ * Takes an item or an array of items and returns an array of items
2565
+ *
2566
+ * 1) Any item except array and undefined returns array with that one item (also null)
2567
+ * 2) Undefined returns empty array
2568
+ * 3) Array returns itself
2569
+ *
2570
+ * @private internal utility
2571
+ */
2572
+ function arrayableToArray(input) {
2573
+ if (input === undefined) {
2574
+ return [];
2575
+ }
2576
+ if (input instanceof Array) {
2577
+ return input;
2578
+ }
2579
+ return [input];
2580
+ }
2581
+
2582
+ /**
2583
+ * Just says that the variable is not used but should be kept
2584
+ * No side effects.
2585
+ *
2586
+ * Note: It can be usefull for:
2587
+ *
2588
+ * 1) Suppressing eager optimization of unused imports
2589
+ * 2) Suppressing eslint errors of unused variables in the tests
2590
+ * 3) Keeping the type of the variable for type testing
2591
+ *
2592
+ * @param value any values
2593
+ * @returns void
2594
+ * @private within the repository
2595
+ */
2596
+ function keepUnused() {
2597
+ var valuesToKeep = [];
2598
+ for (var _i = 0; _i < arguments.length; _i++) {
2599
+ valuesToKeep[_i] = arguments[_i];
2600
+ }
2601
+ }
2602
+
2603
+ /**
2604
+ * Just marks a place of place where should be something implemented
2605
+ * No side effects.
2606
+ *
2607
+ * Note: It can be usefull suppressing eslint errors of unused variables
2608
+ *
2609
+ * @param value any values
2610
+ * @returns void
2611
+ * @private within the repository
2612
+ */
2613
+ function TODO_USE() {
2614
+ var value = [];
2615
+ for (var _i = 0; _i < arguments.length; _i++) {
2616
+ value[_i] = arguments[_i];
2617
+ }
2618
+ }
2619
+
2620
+ /**
2621
+ * Replaces parameters in template with values from parameters object
2622
+ *
2623
+ * @param template the template with parameters in {curly} braces
2624
+ * @param parameters the object with parameters
2625
+ * @returns the template with replaced parameters
2626
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2627
+ * @public exported from `@promptbook/utils`
2628
+ */
2629
+ function replaceParameters(template, parameters) {
2630
+ var e_1, _a;
2631
+ try {
2632
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2633
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2634
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2635
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2636
+ }
2637
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2638
+ // TODO: [🍵]
2639
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2640
+ }
2641
+ }
2642
+ }
2643
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2644
+ finally {
2645
+ try {
2646
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2647
+ }
2648
+ finally { if (e_1) throw e_1.error; }
2649
+ }
2650
+ var replacedTemplate = template;
2651
+ var match;
2652
+ var loopLimit = LOOP_LIMIT;
2653
+ var _loop_1 = function () {
2654
+ if (loopLimit-- < 0) {
2655
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2656
+ }
2657
+ var precol = match.groups.precol;
2658
+ var parameterName = match.groups.parameterName;
2659
+ if (parameterName === '') {
2660
+ return "continue";
2661
+ }
2662
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2663
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
2664
+ }
2665
+ if (parameters[parameterName] === undefined) {
2666
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2667
+ }
2668
+ var parameterValue = parameters[parameterName];
2669
+ if (parameterValue === undefined) {
2670
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2671
+ }
2672
+ parameterValue = parameterValue.toString();
2673
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2674
+ parameterValue = parameterValue
2675
+ .split('\n')
2676
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2677
+ .join('\n');
2678
+ }
2679
+ replacedTemplate =
2680
+ replacedTemplate.substring(0, match.index + precol.length) +
2681
+ parameterValue +
2682
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2683
+ };
2684
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2685
+ .exec(replacedTemplate))) {
2686
+ _loop_1();
2687
+ }
2688
+ // [💫] Check if there are parameters that are not closed properly
2689
+ if (/{\w+$/.test(replacedTemplate)) {
2690
+ throw new PipelineExecutionError('Parameter is not closed');
2691
+ }
2692
+ // [💫] Check if there are parameters that are not opened properly
2693
+ if (/^\w+}/.test(replacedTemplate)) {
2694
+ throw new PipelineExecutionError('Parameter is not opened');
2695
+ }
2696
+ return replacedTemplate;
2697
+ }
2698
+
2699
+ /**
2700
+ * Create difference set of two sets.
2701
+ *
2702
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2703
+ * @public exported from `@promptbook/utils`
2704
+ */
2705
+ function difference(a, b, isEqual) {
2706
+ var e_1, _a;
2707
+ if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2708
+ var diff = new Set();
2709
+ var _loop_1 = function (itemA) {
2710
+ if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2711
+ diff.add(itemA);
2712
+ }
2713
+ };
2714
+ try {
2715
+ for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2590
2716
  var itemA = _c.value;
2591
2717
  _loop_1(itemA);
2592
2718
  }
@@ -2646,600 +2772,98 @@
2646
2772
  }
2647
2773
 
2648
2774
  /**
2649
- * Just marks a place of place where should be something implemented
2650
- * No side effects.
2651
- *
2652
- * Note: It can be usefull suppressing eslint errors of unused variables
2775
+ * @@@
2653
2776
  *
2654
- * @param value any values
2655
- * @returns void
2656
- * @private within the repository
2777
+ * @public exported from `@promptbook/utils`
2657
2778
  */
2658
- function TODO_USE() {
2659
- var value = [];
2660
- for (var _i = 0; _i < arguments.length; _i++) {
2661
- value[_i] = arguments[_i];
2662
- }
2779
+ function deepClone(objectValue) {
2780
+ return JSON.parse(JSON.stringify(objectValue));
2781
+ /*
2782
+ TODO: [🧠] Is there a better implementation?
2783
+ > const propertyNames = Object.getOwnPropertyNames(objectValue);
2784
+ > for (const propertyName of propertyNames) {
2785
+ > const value = (objectValue as really_any)[propertyName];
2786
+ > if (value && typeof value === 'object') {
2787
+ > deepClone(value);
2788
+ > }
2789
+ > }
2790
+ > return Object.assign({}, objectValue);
2791
+ */
2663
2792
  }
2664
-
2665
2793
  /**
2666
- * @@@
2667
- *
2668
- * @public exported from `@promptbook/core`
2794
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
2669
2795
  */
2670
- var MANDATORY_CSV_SETTINGS = Object.freeze({
2671
- header: true,
2672
- // encoding: 'utf8',
2673
- });
2674
2796
 
2675
2797
  /**
2676
- * Definition for CSV spreadsheet
2798
+ * Function `addUsage` will add multiple usages into one
2677
2799
  *
2678
- * @public exported from `@promptbook/core`
2679
- * <- TODO: [🏢] Export from package `@promptbook/csv`
2680
- */
2681
- var CsvFormatDefinition = {
2682
- formatName: 'CSV',
2683
- aliases: ['SPREADSHEET', 'TABLE'],
2684
- isValid: function (value, settings, schema) {
2685
- // TODO: !!!!!! Implement CSV validation
2686
- TODO_USE(value /* <- TODO: Use value here */);
2687
- TODO_USE(settings /* <- TODO: Use settings here */);
2688
- TODO_USE(schema /* <- TODO: Use schema here */);
2689
- return true;
2690
- },
2691
- canBeValid: function (partialValue, settings, schema) {
2692
- TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2693
- TODO_USE(settings /* <- TODO: Use settings here */);
2694
- TODO_USE(schema /* <- TODO: Use schema here */);
2695
- return true;
2696
- },
2697
- heal: function (value, settings, schema) {
2698
- TODO_USE(value /* <- TODO: Use partialValue here */);
2699
- TODO_USE(settings /* <- TODO: Use settings here */);
2700
- TODO_USE(schema /* <- TODO: Use schema here */);
2701
- throw new Error('Not implemented');
2702
- },
2703
- subvalueDefinitions: [
2704
- {
2705
- subvalueName: 'ROW',
2706
- mapValues: function (value, settings, mapCallback) {
2707
- return __awaiter(this, void 0, void 0, function () {
2708
- var csv, mappedData;
2709
- var _this = this;
2710
- return __generator(this, function (_a) {
2711
- switch (_a.label) {
2712
- case 0:
2713
- csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2714
- if (csv.errors.length !== 0) {
2715
- throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2716
- 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 "); }));
2717
- }
2718
- return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2719
- var _a;
2720
- var _b;
2721
- return __generator(this, function (_c) {
2722
- switch (_c.label) {
2723
- case 0:
2724
- _a = [__assign({}, row)];
2725
- _b = {};
2726
- // <- TODO: !!!!!! Dynamic new column name and position
2727
- // <- TODO: !!!!!! Check name collisions
2728
- return [4 /*yield*/, mapCallback(row, index)];
2729
- case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
2730
- // <- TODO: !!!!!! Dynamic new column name and position
2731
- // <- TODO: !!!!!! Check name collisions
2732
- _c.sent(), _b)])))];
2733
- }
2734
- });
2735
- }); }))];
2736
- case 1:
2737
- mappedData = _a.sent();
2738
- return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2739
- }
2740
- });
2741
- });
2742
- },
2743
- },
2744
- {
2745
- subvalueName: 'CELL',
2746
- mapValues: function (value, settings, mapCallback) {
2747
- return __awaiter(this, void 0, void 0, function () {
2748
- var csv, mappedData;
2749
- var _this = this;
2750
- return __generator(this, function (_a) {
2751
- switch (_a.label) {
2752
- case 0:
2753
- csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2754
- if (csv.errors.length !== 0) {
2755
- throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2756
- 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 "); }));
2757
- }
2758
- return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2759
- var _this = this;
2760
- return __generator(this, function (_a) {
2761
- return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2762
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
2763
- return __awaiter(_this, void 0, void 0, function () {
2764
- var index;
2765
- var _c;
2766
- return __generator(this, function (_d) {
2767
- index = rowIndex * Object.keys(row).length + columnIndex;
2768
- return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2769
- });
2770
- });
2771
- }))];
2772
- });
2773
- }); }))];
2774
- case 1:
2775
- mappedData = _a.sent();
2776
- return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2777
- }
2778
- });
2779
- });
2780
- },
2781
- },
2782
- ],
2783
- };
2784
- /**
2785
- * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2786
- * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2787
- * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2788
- * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2789
- * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2790
- */
2791
-
2792
- /**
2793
- * Function isValidJsonString will tell you if the string is valid JSON or not
2794
- *
2795
- * @public exported from `@promptbook/utils`
2796
- */
2797
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2798
- try {
2799
- JSON.parse(value);
2800
- return true;
2801
- }
2802
- catch (error) {
2803
- if (!(error instanceof Error)) {
2804
- throw error;
2805
- }
2806
- if (error.message.includes('Unexpected token')) {
2807
- return false;
2808
- }
2809
- return false;
2810
- }
2811
- }
2812
-
2813
- /**
2814
- * Definition for JSON format
2815
- *
2816
- * @private still in development [🏢]
2817
- */
2818
- var JsonFormatDefinition = {
2819
- formatName: 'JSON',
2820
- mimeType: 'application/json',
2821
- isValid: function (value, settings, schema) {
2822
- TODO_USE(schema /* <- TODO: Use schema here */);
2823
- TODO_USE(settings /* <- TODO: Use settings here */);
2824
- return isValidJsonString(value);
2825
- },
2826
- canBeValid: function (partialValue, settings, schema) {
2827
- TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2828
- TODO_USE(settings /* <- TODO: Use settings here */);
2829
- TODO_USE(schema /* <- TODO: Use schema here */);
2830
- return true;
2831
- },
2832
- heal: function (value, settings, schema) {
2833
- TODO_USE(value /* <- TODO: Use partialValue here */);
2834
- TODO_USE(settings /* <- TODO: Use settings here */);
2835
- TODO_USE(schema /* <- TODO: Use schema here */);
2836
- throw new Error('Not implemented');
2837
- },
2838
- subvalueDefinitions: [],
2839
- };
2840
- /**
2841
- * TODO: [🧠] Maybe propper instance of object
2842
- * TODO: [0] Make string_serialized_json
2843
- * TODO: [1] Make type for JSON Settings and Schema
2844
- * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2845
- * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2846
- * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2847
- * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2848
- * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2849
- * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2850
- */
2851
-
2852
- /**
2853
- * Definition for any text - this will be always valid
2854
- *
2855
- * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
2800
+ * Note: If you provide 0 values, it returns ZERO_USAGE
2856
2801
  *
2857
2802
  * @public exported from `@promptbook/core`
2858
2803
  */
2859
- var TextFormatDefinition = {
2860
- formatName: 'TEXT',
2861
- isValid: function (value) {
2862
- return typeof value === 'string';
2863
- },
2864
- canBeValid: function (partialValue) {
2865
- return typeof partialValue === 'string';
2866
- },
2867
- heal: function () {
2868
- throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
2869
- },
2870
- subvalueDefinitions: [
2871
- {
2872
- subvalueName: 'LINE',
2873
- mapValues: function (value, settings, mapCallback) {
2874
- return __awaiter(this, void 0, void 0, function () {
2875
- var lines, mappedLines;
2876
- return __generator(this, function (_a) {
2877
- switch (_a.label) {
2878
- case 0:
2879
- lines = value.split('\n');
2880
- return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
2881
- // TODO: [🧠] Maybe option to skip empty line
2882
- /* not await */ return mapCallback({
2883
- lineContent: lineContent,
2884
- // TODO: [🧠] Maybe also put here `lineNumber`
2885
- }, lineNumber);
2886
- }))];
2887
- case 1:
2888
- mappedLines = _a.sent();
2889
- return [2 /*return*/, mappedLines.join('\n')];
2890
- }
2891
- });
2892
- });
2893
- },
2894
- },
2895
- // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2896
- ],
2897
- };
2898
- /**
2899
- * TODO: [1] Make type for XML Text and Schema
2900
- * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
2901
- * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
2902
- * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
2903
- * TODO: [🍓] In `TextFormatDefinition` implement `heal
2904
- * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
2905
- * TODO: [🏢] Allow to expect something inside each item of list and other formats
2906
- */
2907
-
2908
- /**
2909
- * Definition for XML format
2910
- *
2911
- * @private still in development [🏢]
2912
- */
2913
- var XmlFormatDefinition = {
2914
- formatName: 'XML',
2915
- mimeType: 'application/xml',
2916
- isValid: function (value, settings, schema) {
2917
- TODO_USE(value /* <- TODO: Use value here */);
2918
- TODO_USE(settings /* <- TODO: Use settings here */);
2919
- TODO_USE(schema /* <- TODO: Use schema here */);
2920
- return true;
2921
- },
2922
- canBeValid: function (partialValue, settings, schema) {
2923
- TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2924
- TODO_USE(settings /* <- TODO: Use settings here */);
2925
- TODO_USE(schema /* <- TODO: Use schema here */);
2926
- return true;
2927
- },
2928
- heal: function (value, settings, schema) {
2929
- TODO_USE(value /* <- TODO: Use partialValue here */);
2930
- TODO_USE(settings /* <- TODO: Use settings here */);
2931
- TODO_USE(schema /* <- TODO: Use schema here */);
2932
- throw new Error('Not implemented');
2933
- },
2934
- subvalueDefinitions: [],
2935
- };
2936
- /**
2937
- * TODO: [🧠] Maybe propper instance of object
2938
- * TODO: [0] Make string_serialized_xml
2939
- * TODO: [1] Make type for XML Settings and Schema
2940
- * TODO: [🧠] What to use for validating XMLs - XSD,...
2941
- * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
2942
- * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
2943
- * TODO: [🍓] In `XmlFormatDefinition` implement `heal
2944
- * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
2945
- * TODO: [🏢] Allow to expect something inside XML and other formats
2946
- */
2947
-
2948
- /**
2949
- * Definitions for all formats supported by Promptbook
2950
- *
2951
- * @private internal index of `...` <- TODO [🏢]
2952
- */
2953
- var FORMAT_DEFINITIONS = [
2954
- JsonFormatDefinition,
2955
- XmlFormatDefinition,
2956
- TextFormatDefinition,
2957
- CsvFormatDefinition,
2958
- ];
2959
-
2960
- /**
2961
- * Maps available parameters to expected parameters
2962
- *
2963
- * The strategy is:
2964
- * 1) @@@
2965
- * 2) @@@
2966
- *
2967
- * @throws {PipelineExecutionError} @@@
2968
- * @private within the repository used in `createPipelineExecutor`
2969
- */
2970
- function mapAvailableToExpectedParameters(options) {
2971
- var e_1, _a;
2972
- var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
2973
- var availableParametersNames = new Set(Object.keys(availableParameters));
2974
- var expectedParameterNames = new Set(Object.keys(expectedParameters));
2975
- var mappedParameters = {};
2976
- try {
2977
- // Phase 1️⃣: Matching mapping
2978
- for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
2979
- var parameterName = _c.value;
2980
- // Situation: Parameter is available and expected
2981
- if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2982
- mappedParameters[parameterName] = availableParameters[parameterName];
2983
- // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
2984
- availableParametersNames.delete(parameterName);
2985
- expectedParameterNames.delete(parameterName);
2986
- }
2987
- // Situation: Parameter is available but NOT expected
2988
- else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
2989
- // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
2990
- }
2991
- // Situation: Parameter is NOT available BUT expected
2992
- else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
2993
- // Do nothing here - this will be maybe fixed in the non-matching mapping
2994
- }
2995
- }
2804
+ function addUsage() {
2805
+ var usageItems = [];
2806
+ for (var _i = 0; _i < arguments.length; _i++) {
2807
+ usageItems[_i] = arguments[_i];
2996
2808
  }
2997
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2998
- finally {
2809
+ return usageItems.reduce(function (acc, item) {
2810
+ var e_1, _a, e_2, _b;
2811
+ var _c;
2812
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
2999
2813
  try {
3000
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3001
- }
3002
- finally { if (e_1) throw e_1.error; }
3003
- }
3004
- if (expectedParameterNames.size === 0) {
3005
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3006
- Object.freeze(mappedParameters);
3007
- return mappedParameters;
3008
- }
3009
- // Phase 2️⃣: Non-matching mapping
3010
- if (expectedParameterNames.size !== availableParametersNames.size) {
3011
- 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)
3012
- .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3013
- .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3014
- .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3015
- .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3016
- .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3017
- .join('\n')), "\n\n "); }));
3018
- }
3019
- var expectedParameterNamesArray = Array.from(expectedParameterNames);
3020
- var availableParametersNamesArray = Array.from(availableParametersNames);
3021
- for (var i = 0; i < expectedParameterNames.size; i++) {
3022
- mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3023
- }
3024
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3025
- Object.freeze(mappedParameters);
3026
- return mappedParameters;
3027
- }
3028
-
3029
- /**
3030
- * Extracts all code blocks from markdown.
3031
- *
3032
- * Note: There are multiple simmilar function:
3033
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3034
- * - `extractJsonBlock` extracts exactly one valid JSON code block
3035
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3036
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3037
- *
3038
- * @param markdown any valid markdown
3039
- * @returns code blocks with language and content
3040
- * @throws {ParseError} if block is not closed properly
3041
- * @public exported from `@promptbook/markdown-utils`
3042
- */
3043
- function extractAllBlocksFromMarkdown(markdown) {
3044
- var e_1, _a;
3045
- var codeBlocks = [];
3046
- var lines = markdown.split('\n');
3047
- // Note: [0] Ensure that the last block notated by gt > will be closed
3048
- lines.push('');
3049
- var currentCodeBlock = null;
3050
- try {
3051
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3052
- var line = lines_1_1.value;
3053
- if (line.startsWith('> ') || line === '>') {
3054
- if (currentCodeBlock === null) {
3055
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3056
- } /* not else */
3057
- if (currentCodeBlock.blockNotation === '>') {
3058
- if (currentCodeBlock.content !== '') {
3059
- currentCodeBlock.content += '\n';
3060
- }
3061
- currentCodeBlock.content += line.slice(2);
3062
- }
3063
- }
3064
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3065
- codeBlocks.push(currentCodeBlock);
3066
- currentCodeBlock = null;
3067
- }
3068
- /* not else */
3069
- if (line.startsWith('```')) {
3070
- var language = line.slice(3).trim() || null;
3071
- if (currentCodeBlock === null) {
3072
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3073
- }
3074
- else {
3075
- if (language !== null) {
3076
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2814
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
2815
+ var key = _e.value;
2816
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2817
+ //@ts-ignore
2818
+ if (item.input[key]) {
2819
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2820
+ //@ts-ignore
2821
+ acc.input[key].value += item.input[key].value || 0;
2822
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2823
+ //@ts-ignore
2824
+ if (item.input[key].isUncertain) {
2825
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2826
+ //@ts-ignore
2827
+ acc.input[key].isUncertain = true;
3077
2828
  }
3078
- codeBlocks.push(currentCodeBlock);
3079
- currentCodeBlock = null;
3080
- }
3081
- }
3082
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3083
- if (currentCodeBlock.content !== '') {
3084
- currentCodeBlock.content += '\n';
3085
2829
  }
3086
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3087
2830
  }
3088
2831
  }
3089
- }
3090
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3091
- finally {
3092
- try {
3093
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3094
- }
3095
- finally { if (e_1) throw e_1.error; }
3096
- }
3097
- if (currentCodeBlock !== null) {
3098
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3099
- }
3100
- return codeBlocks;
3101
- }
3102
- /**
3103
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3104
- */
3105
-
3106
- /**
3107
- * Extracts extracts exactly one valid JSON code block
3108
- *
3109
- * - When given string is a valid JSON as it is, it just returns it
3110
- * - When there is no JSON code block the function throws a `ParseError`
3111
- * - When there are multiple JSON code blocks the function throws a `ParseError`
3112
- *
3113
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
3114
- * Note: There are multiple simmilar function:
3115
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3116
- * - `extractJsonBlock` extracts exactly one valid JSON code block
3117
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3118
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3119
- *
3120
- * @public exported from `@promptbook/markdown-utils`
3121
- * @throws {ParseError} if there is no valid JSON block in the markdown
3122
- */
3123
- function extractJsonBlock(markdown) {
3124
- if (isValidJsonString(markdown)) {
3125
- return markdown;
3126
- }
3127
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3128
- var jsonBlocks = codeBlocks.filter(function (_a) {
3129
- var content = _a.content;
3130
- return isValidJsonString(content);
3131
- });
3132
- if (jsonBlocks.length === 0) {
3133
- throw new Error('There is no valid JSON block in the markdown');
3134
- }
3135
- if (jsonBlocks.length > 1) {
3136
- throw new Error('There are multiple JSON code blocks in the markdown');
3137
- }
3138
- return jsonBlocks[0].content;
3139
- }
3140
- /**
3141
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3142
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3143
- */
3144
-
3145
- /**
3146
- * Just says that the variable is not used but should be kept
3147
- * No side effects.
3148
- *
3149
- * Note: It can be usefull for:
3150
- *
3151
- * 1) Suppressing eager optimization of unused imports
3152
- * 2) Suppressing eslint errors of unused variables in the tests
3153
- * 3) Keeping the type of the variable for type testing
3154
- *
3155
- * @param value any values
3156
- * @returns void
3157
- * @private within the repository
3158
- */
3159
- function keepUnused() {
3160
- var valuesToKeep = [];
3161
- for (var _i = 0; _i < arguments.length; _i++) {
3162
- valuesToKeep[_i] = arguments[_i];
3163
- }
3164
- }
3165
-
3166
- /**
3167
- * Replaces parameters in template with values from parameters object
3168
- *
3169
- * @param template the template with parameters in {curly} braces
3170
- * @param parameters the object with parameters
3171
- * @returns the template with replaced parameters
3172
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3173
- * @public exported from `@promptbook/utils`
3174
- */
3175
- function replaceParameters(template, parameters) {
3176
- var e_1, _a;
3177
- try {
3178
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3179
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3180
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3181
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3182
- }
3183
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3184
- // TODO: [🍵]
3185
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2832
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2833
+ finally {
2834
+ try {
2835
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
3186
2836
  }
2837
+ finally { if (e_1) throw e_1.error; }
3187
2838
  }
3188
- }
3189
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3190
- finally {
3191
2839
  try {
3192
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3193
- }
3194
- finally { if (e_1) throw e_1.error; }
3195
- }
3196
- var replacedTemplate = template;
3197
- var match;
3198
- var loopLimit = LOOP_LIMIT;
3199
- var _loop_1 = function () {
3200
- if (loopLimit-- < 0) {
3201
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3202
- }
3203
- var precol = match.groups.precol;
3204
- var parameterName = match.groups.parameterName;
3205
- if (parameterName === '') {
3206
- return "continue";
3207
- }
3208
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3209
- throw new PipelineExecutionError('Parameter is already opened or not closed');
3210
- }
3211
- if (parameters[parameterName] === undefined) {
3212
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3213
- }
3214
- var parameterValue = parameters[parameterName];
3215
- if (parameterValue === undefined) {
3216
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3217
- }
3218
- parameterValue = parameterValue.toString();
3219
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3220
- parameterValue = parameterValue
3221
- .split('\n')
3222
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3223
- .join('\n');
2840
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
2841
+ var key = _g.value;
2842
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2843
+ //@ts-ignore
2844
+ if (item.output[key]) {
2845
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2846
+ //@ts-ignore
2847
+ acc.output[key].value += item.output[key].value || 0;
2848
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2849
+ //@ts-ignore
2850
+ if (item.output[key].isUncertain) {
2851
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2852
+ //@ts-ignore
2853
+ acc.output[key].isUncertain = true;
2854
+ }
2855
+ }
2856
+ }
3224
2857
  }
3225
- replacedTemplate =
3226
- replacedTemplate.substring(0, match.index + precol.length) +
3227
- parameterValue +
3228
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3229
- };
3230
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3231
- .exec(replacedTemplate))) {
3232
- _loop_1();
3233
- }
3234
- // [💫] Check if there are parameters that are not closed properly
3235
- if (/{\w+$/.test(replacedTemplate)) {
3236
- throw new PipelineExecutionError('Parameter is not closed');
3237
- }
3238
- // [💫] Check if there are parameters that are not opened properly
3239
- if (/^\w+}/.test(replacedTemplate)) {
3240
- throw new PipelineExecutionError('Parameter is not opened');
3241
- }
3242
- return replacedTemplate;
2858
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2859
+ finally {
2860
+ try {
2861
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2862
+ }
2863
+ finally { if (e_2) throw e_2.error; }
2864
+ }
2865
+ return acc;
2866
+ }, deepClone(ZERO_USAGE));
3243
2867
  }
3244
2868
 
3245
2869
  /**
@@ -3291,797 +2915,70 @@
3291
2915
  }
3292
2916
 
3293
2917
  /**
3294
- * Split text into sentences
3295
- *
3296
- * @public exported from `@promptbook/utils`
3297
- */
3298
- function splitIntoSentences(text) {
3299
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3300
- }
3301
- /**
3302
- * Counts number of sentences in the text
3303
- *
3304
- * @public exported from `@promptbook/utils`
3305
- */
3306
- function countSentences(text) {
3307
- return splitIntoSentences(text).length;
3308
- }
3309
-
3310
- /**
3311
- * Counts number of words in the text
3312
- *
3313
- * @public exported from `@promptbook/utils`
3314
- */
3315
- function countWords(text) {
3316
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3317
- text = removeDiacritics(text);
3318
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3319
- }
3320
-
3321
- /**
3322
- * Index of all counter functions
3323
- *
3324
- * @public exported from `@promptbook/utils`
3325
- */
3326
- var CountUtils = {
3327
- CHARACTERS: countCharacters,
3328
- WORDS: countWords,
3329
- SENTENCES: countSentences,
3330
- PARAGRAPHS: countParagraphs,
3331
- LINES: countLines,
3332
- PAGES: countPages,
3333
- };
3334
- /**
3335
- * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3336
- */
3337
-
3338
- /**
3339
- * Function checkExpectations will check if the expectations on given value are met
3340
- *
3341
- * Note: There are two simmilar functions:
3342
- * - `checkExpectations` which throws an error if the expectations are not met
3343
- * - `isPassingExpectations` which returns a boolean
3344
- *
3345
- * @throws {ExpectError} if the expectations are not met
3346
- * @returns {void} Nothing
3347
- * @private internal function of `createPipelineExecutor`
3348
- */
3349
- function checkExpectations(expectations, value) {
3350
- var e_1, _a;
3351
- try {
3352
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3353
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3354
- var amount = CountUtils[unit.toUpperCase()](value);
3355
- if (min && amount < min) {
3356
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3357
- } /* not else */
3358
- if (max && amount > max) {
3359
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3360
- }
3361
- }
3362
- }
3363
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3364
- finally {
3365
- try {
3366
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3367
- }
3368
- finally { if (e_1) throw e_1.error; }
3369
- }
3370
- }
3371
- /**
3372
- * TODO: [💝] Unite object for expecting amount and format
3373
- * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3374
- * Note: [💝] and [🤠] are interconnected together
3375
- */
3376
-
3377
- /**
3378
- * @@@
3379
- *
3380
- * @private internal utility of `createPipelineExecutor`
3381
- */
3382
- function executeAttempts(options) {
3383
- return __awaiter(this, void 0, void 0, function () {
3384
- var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3385
- return __generator(this, function (_a) {
3386
- switch (_a.label) {
3387
- case 0:
3388
- 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;
3389
- maxExecutionAttempts = settings.maxExecutionAttempts;
3390
- $ongoingTemplateResult = {
3391
- $result: null,
3392
- $resultString: null,
3393
- $expectError: null,
3394
- $scriptPipelineExecutionErrors: [],
3395
- };
3396
- _loop_1 = function (attempt) {
3397
- 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;
3398
- var e_1, _q, e_3, _r, e_2, _s;
3399
- return __generator(this, function (_t) {
3400
- switch (_t.label) {
3401
- case 0:
3402
- isJokerAttempt = attempt < 0;
3403
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3404
- // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3405
- if (isJokerAttempt && !jokerParameterName) {
3406
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3407
- }
3408
- $ongoingTemplateResult.$result = null;
3409
- $ongoingTemplateResult.$resultString = null;
3410
- $ongoingTemplateResult.$expectError = null;
3411
- if (isJokerAttempt) {
3412
- if (parameters[jokerParameterName] === undefined) {
3413
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3414
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3415
- }
3416
- else {
3417
- $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3418
- }
3419
- }
3420
- _t.label = 1;
3421
- case 1:
3422
- _t.trys.push([1, 43, 44, 45]);
3423
- if (!!isJokerAttempt) return [3 /*break*/, 25];
3424
- _b = template.templateType;
3425
- switch (_b) {
3426
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3427
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3428
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3429
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3430
- }
3431
- return [3 /*break*/, 24];
3432
- case 2:
3433
- $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3434
- return [3 /*break*/, 25];
3435
- case 3:
3436
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3437
- $ongoingTemplateResult.$prompt = {
3438
- title: template.title,
3439
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3440
- ? preparedPipeline.pipelineUrl
3441
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3442
- parameters: parameters,
3443
- content: preparedContent,
3444
- modelRequirements: modelRequirements,
3445
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3446
- var name = _a.name;
3447
- return name === template.personaName;
3448
- }) ||
3449
- {})), template.expectations),
3450
- format: template.format,
3451
- postprocessingFunctionNames: template.postprocessingFunctionNames,
3452
- }; // <- TODO: Not very good type guard
3453
- _c = modelRequirements.modelVariant;
3454
- switch (_c) {
3455
- case 'CHAT': return [3 /*break*/, 4];
3456
- case 'COMPLETION': return [3 /*break*/, 6];
3457
- case 'EMBEDDING': return [3 /*break*/, 8];
3458
- }
3459
- return [3 /*break*/, 9];
3460
- case 4:
3461
- _d = $ongoingTemplateResult;
3462
- return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3463
- case 5:
3464
- _d.$chatResult = _t.sent();
3465
- // TODO: [🍬] Destroy chatThread
3466
- $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3467
- $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3468
- return [3 /*break*/, 10];
3469
- case 6:
3470
- _e = $ongoingTemplateResult;
3471
- return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3472
- case 7:
3473
- _e.$completionResult = _t.sent();
3474
- $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3475
- $ongoingTemplateResult.$resultString =
3476
- $ongoingTemplateResult.$completionResult.content;
3477
- return [3 /*break*/, 10];
3478
- 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 "); }));
3479
- 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 "); }));
3480
- case 10: return [3 /*break*/, 25];
3481
- case 11:
3482
- if (arrayableToArray(tools.script).length === 0) {
3483
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3484
- }
3485
- if (!template.contentLanguage) {
3486
- 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 "); }));
3487
- }
3488
- _t.label = 12;
3489
- case 12:
3490
- _t.trys.push([12, 19, 20, 21]);
3491
- _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3492
- _t.label = 13;
3493
- case 13:
3494
- if (!!_g.done) return [3 /*break*/, 18];
3495
- scriptTools = _g.value;
3496
- _t.label = 14;
3497
- case 14:
3498
- _t.trys.push([14, 16, , 17]);
3499
- _h = $ongoingTemplateResult;
3500
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3501
- scriptLanguage: template.contentLanguage,
3502
- script: preparedContent,
3503
- parameters: parameters,
3504
- }))];
3505
- case 15:
3506
- _h.$resultString = _t.sent();
3507
- return [3 /*break*/, 18];
3508
- case 16:
3509
- error_1 = _t.sent();
3510
- if (!(error_1 instanceof Error)) {
3511
- throw error_1;
3512
- }
3513
- if (error_1 instanceof UnexpectedError) {
3514
- throw error_1;
3515
- }
3516
- $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3517
- return [3 /*break*/, 17];
3518
- case 17:
3519
- _g = _f.next();
3520
- return [3 /*break*/, 13];
3521
- case 18: return [3 /*break*/, 21];
3522
- case 19:
3523
- e_1_1 = _t.sent();
3524
- e_1 = { error: e_1_1 };
3525
- return [3 /*break*/, 21];
3526
- case 20:
3527
- try {
3528
- if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3529
- }
3530
- finally { if (e_1) throw e_1.error; }
3531
- return [7 /*endfinally*/];
3532
- case 21:
3533
- if ($ongoingTemplateResult.$resultString !== null) {
3534
- return [3 /*break*/, 25];
3535
- }
3536
- if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3537
- throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3538
- }
3539
- else {
3540
- 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
3541
- .map(function (error) { return '- ' + error.message; })
3542
- .join('\n\n')), "\n "); }));
3543
- }
3544
- case 22:
3545
- if (tools.userInterface === undefined) {
3546
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3547
- }
3548
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3549
- _j = $ongoingTemplateResult;
3550
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3551
- promptTitle: template.title,
3552
- promptMessage: replaceParameters(template.description || '', parameters),
3553
- defaultValue: replaceParameters(preparedContent, parameters),
3554
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3555
- placeholder: undefined,
3556
- priority: priority,
3557
- }))];
3558
- case 23:
3559
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3560
- _j.$resultString = _t.sent();
3561
- return [3 /*break*/, 25];
3562
- case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3563
- case 25:
3564
- if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3565
- _t.label = 26;
3566
- case 26:
3567
- _t.trys.push([26, 40, 41, 42]);
3568
- _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3569
- _t.label = 27;
3570
- case 27:
3571
- if (!!_l.done) return [3 /*break*/, 39];
3572
- functionName = _l.value;
3573
- postprocessingError = null;
3574
- _t.label = 28;
3575
- case 28:
3576
- _t.trys.push([28, 35, 36, 37]);
3577
- _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3578
- _t.label = 29;
3579
- case 29:
3580
- if (!!_o.done) return [3 /*break*/, 34];
3581
- scriptTools = _o.value;
3582
- _t.label = 30;
3583
- case 30:
3584
- _t.trys.push([30, 32, , 33]);
3585
- _p = $ongoingTemplateResult;
3586
- return [4 /*yield*/, scriptTools.execute({
3587
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3588
- script: "".concat(functionName, "(resultString)"),
3589
- parameters: {
3590
- resultString: $ongoingTemplateResult.$resultString || '',
3591
- // Note: No ...parametersForTemplate, because working with result only
3592
- },
3593
- })];
3594
- case 31:
3595
- _p.$resultString = _t.sent();
3596
- postprocessingError = null;
3597
- return [3 /*break*/, 34];
3598
- case 32:
3599
- error_2 = _t.sent();
3600
- if (!(error_2 instanceof Error)) {
3601
- throw error_2;
3602
- }
3603
- if (error_2 instanceof UnexpectedError) {
3604
- throw error_2;
3605
- }
3606
- postprocessingError = error_2;
3607
- $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3608
- return [3 /*break*/, 33];
3609
- case 33:
3610
- _o = _m.next();
3611
- return [3 /*break*/, 29];
3612
- case 34: return [3 /*break*/, 37];
3613
- case 35:
3614
- e_2_1 = _t.sent();
3615
- e_2 = { error: e_2_1 };
3616
- return [3 /*break*/, 37];
3617
- case 36:
3618
- try {
3619
- if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3620
- }
3621
- finally { if (e_2) throw e_2.error; }
3622
- return [7 /*endfinally*/];
3623
- case 37:
3624
- if (postprocessingError) {
3625
- throw postprocessingError;
3626
- }
3627
- _t.label = 38;
3628
- case 38:
3629
- _l = _k.next();
3630
- return [3 /*break*/, 27];
3631
- case 39: return [3 /*break*/, 42];
3632
- case 40:
3633
- e_3_1 = _t.sent();
3634
- e_3 = { error: e_3_1 };
3635
- return [3 /*break*/, 42];
3636
- case 41:
3637
- try {
3638
- if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3639
- }
3640
- finally { if (e_3) throw e_3.error; }
3641
- return [7 /*endfinally*/];
3642
- case 42:
3643
- // TODO: [💝] Unite object for expecting amount and format
3644
- if (template.format) {
3645
- if (template.format === 'JSON') {
3646
- if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3647
- // TODO: [🏢] Do more universally via `FormatDefinition`
3648
- try {
3649
- $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3650
- }
3651
- catch (error) {
3652
- keepUnused(error);
3653
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3654
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3655
- }
3656
- }
3657
- }
3658
- else {
3659
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3660
- }
3661
- }
3662
- // TODO: [💝] Unite object for expecting amount and format
3663
- if (template.expectations) {
3664
- checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3665
- }
3666
- return [2 /*return*/, "break-attempts"];
3667
- case 43:
3668
- error_3 = _t.sent();
3669
- if (!(error_3 instanceof ExpectError)) {
3670
- throw error_3;
3671
- }
3672
- $ongoingTemplateResult.$expectError = error_3;
3673
- return [3 /*break*/, 45];
3674
- case 44:
3675
- if (!isJokerAttempt &&
3676
- template.templateType === 'PROMPT_TEMPLATE' &&
3677
- $ongoingTemplateResult.$prompt
3678
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3679
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3680
- ) {
3681
- // TODO: [🧠] Maybe put other templateTypes into report
3682
- $executionReport.promptExecutions.push({
3683
- prompt: __assign({}, $ongoingTemplateResult.$prompt),
3684
- result: $ongoingTemplateResult.$result || undefined,
3685
- error: $ongoingTemplateResult.$expectError === null
3686
- ? undefined
3687
- : serializeError($ongoingTemplateResult.$expectError),
3688
- });
3689
- }
3690
- return [7 /*endfinally*/];
3691
- case 45:
3692
- if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3693
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3694
- var _a, _b, _c;
3695
- 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) || '')
3696
- .split('\n')
3697
- .map(function (line) { return "> ".concat(line); })
3698
- .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) || '')
3699
- .split('\n')
3700
- .map(function (line) { return "> ".concat(line); })
3701
- .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3702
- ? 'null'
3703
- : $ongoingTemplateResult.$resultString
3704
- .split('\n')
3705
- .map(function (line) { return "> ".concat(line); })
3706
- .join('\n')), "\n ---\n ");
3707
- }));
3708
- }
3709
- return [2 /*return*/];
3710
- }
3711
- });
3712
- };
3713
- attempt = -jokerParameterNames.length;
3714
- _a.label = 1;
3715
- case 1:
3716
- if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3717
- return [5 /*yield**/, _loop_1(attempt)];
3718
- case 2:
3719
- state_1 = _a.sent();
3720
- switch (state_1) {
3721
- case "break-attempts": return [3 /*break*/, 4];
3722
- }
3723
- _a.label = 3;
3724
- case 3:
3725
- attempt++;
3726
- return [3 /*break*/, 1];
3727
- case 4:
3728
- if ($ongoingTemplateResult.$resultString === null) {
3729
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3730
- }
3731
- return [2 /*return*/, $ongoingTemplateResult.$resultString];
3732
- }
3733
- });
3734
- });
3735
- }
3736
- /**
3737
- * TODO: Break into smaller functions
3738
- */
3739
-
3740
- /**
3741
- * @@@
3742
- *
3743
- * @private internal utility of `createPipelineExecutor`
3744
- */
3745
- function executeFormatCells(options) {
3746
- return __awaiter(this, void 0, void 0, function () {
3747
- var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3748
- var _this = this;
3749
- return __generator(this, function (_a) {
3750
- switch (_a.label) {
3751
- case 0:
3752
- template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3753
- if (template.foreach === undefined) {
3754
- return [2 /*return*/, /* not await */ executeAttempts(options)];
3755
- }
3756
- if (jokerParameterNames.length !== 0) {
3757
- 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 "); }));
3758
- }
3759
- parameterValue = parameters[template.foreach.parameterName] || '';
3760
- formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3761
- return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3762
- });
3763
- if (formatDefinition === undefined) {
3764
- throw new UnexpectedError(
3765
- // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3766
- 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; })
3767
- .map(function (formatName) { return "- ".concat(formatName); })
3768
- .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3769
- }
3770
- subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3771
- return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3772
- });
3773
- if (subvalueDefinition === undefined) {
3774
- throw new UnexpectedError(
3775
- // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3776
- 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
3777
- .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3778
- .map(function (subvalueName) { return "- ".concat(subvalueName); })
3779
- .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3780
- }
3781
- if (formatDefinition.formatName === 'CSV') {
3782
- formatSettings = settings.csvSettings;
3783
- // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3784
- }
3785
- return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3786
- var mappedParameters, allSubparameters, subresultString;
3787
- return __generator(this, function (_a) {
3788
- switch (_a.label) {
3789
- case 0:
3790
- // TODO: !!!!!!! Limit to N concurrent executions
3791
- // TODO: !!!!!!! Report progress
3792
- try {
3793
- mappedParameters = mapAvailableToExpectedParameters({
3794
- expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3795
- availableParameters: subparameters,
3796
- });
3797
- }
3798
- catch (error) {
3799
- if (!(error instanceof PipelineExecutionError)) {
3800
- throw error;
3801
- }
3802
- 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 "); }));
3803
- }
3804
- allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3805
- // 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
3806
- Object.freeze(allSubparameters);
3807
- return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
3808
- case 1:
3809
- subresultString = _a.sent();
3810
- return [2 /*return*/, subresultString];
3811
- }
3812
- });
3813
- }); })];
3814
- case 1:
3815
- resultString = _a.sent();
3816
- return [2 /*return*/, resultString];
3817
- }
3818
- });
3819
- });
3820
- }
3821
- /**
3822
- * TODO: !!!!!! Make pipelineIdentification more precise
3823
- * TODO: !!!!!! How FOREACH execution looks in the report
3824
- */
3825
-
3826
- /**
3827
- * @@@
3828
- *
3829
- * @private internal utility of `createPipelineExecutor`
3830
- */
3831
- function getContextForTemplate(template) {
3832
- return __awaiter(this, void 0, void 0, function () {
3833
- return __generator(this, function (_a) {
3834
- TODO_USE(template);
3835
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3836
- });
3837
- });
3838
- }
3839
-
3840
- /**
3841
- * @@@
3842
- *
3843
- * @private internal utility of `createPipelineExecutor`
3844
- */
3845
- function getKnowledgeForTemplate(options) {
3846
- return __awaiter(this, void 0, void 0, function () {
3847
- var preparedPipeline, template;
3848
- return __generator(this, function (_a) {
3849
- preparedPipeline = options.preparedPipeline, template = options.template;
3850
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3851
- TODO_USE(template);
3852
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3853
- var content = _a.content;
3854
- return "- ".concat(content);
3855
- }).join('\n')];
3856
- });
3857
- });
3858
- }
3859
-
3860
- /**
3861
- * @@@
3862
- *
3863
- * @private internal utility of `createPipelineExecutor`
3864
- */
3865
- function getSamplesForTemplate(template) {
3866
- return __awaiter(this, void 0, void 0, function () {
3867
- return __generator(this, function (_a) {
3868
- // TODO: [♨] Implement Better - use real index and keyword search
3869
- TODO_USE(template);
3870
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3871
- });
3872
- });
3873
- }
3874
-
3875
- /**
3876
- * @@@
3877
- *
3878
- * @private internal utility of `createPipelineExecutor`
3879
- */
3880
- function getReservedParametersForTemplate(options) {
3881
- return __awaiter(this, void 0, void 0, function () {
3882
- var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3883
- var e_1, _a;
3884
- return __generator(this, function (_b) {
3885
- switch (_b.label) {
3886
- case 0:
3887
- preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3888
- return [4 /*yield*/, getContextForTemplate(template)];
3889
- case 1:
3890
- context = _b.sent();
3891
- return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3892
- case 2:
3893
- knowledge = _b.sent();
3894
- return [4 /*yield*/, getSamplesForTemplate(template)];
3895
- case 3:
3896
- samples = _b.sent();
3897
- currentDate = new Date().toISOString();
3898
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3899
- reservedParameters = {
3900
- content: RESERVED_PARAMETER_RESTRICTED,
3901
- context: context,
3902
- knowledge: knowledge,
3903
- samples: samples,
3904
- currentDate: currentDate,
3905
- modelName: modelName,
3906
- };
3907
- _loop_1 = function (parameterName) {
3908
- if (reservedParameters[parameterName] === undefined) {
3909
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3910
- }
3911
- };
3912
- try {
3913
- // Note: Doublecheck that ALL reserved parameters are defined:
3914
- 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()) {
3915
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3916
- _loop_1(parameterName);
3917
- }
3918
- }
3919
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3920
- finally {
3921
- try {
3922
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3923
- }
3924
- finally { if (e_1) throw e_1.error; }
3925
- }
3926
- return [2 /*return*/, reservedParameters];
3927
- }
3928
- });
3929
- });
2918
+ * Split text into sentences
2919
+ *
2920
+ * @public exported from `@promptbook/utils`
2921
+ */
2922
+ function splitIntoSentences(text) {
2923
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
2924
+ }
2925
+ /**
2926
+ * Counts number of sentences in the text
2927
+ *
2928
+ * @public exported from `@promptbook/utils`
2929
+ */
2930
+ function countSentences(text) {
2931
+ return splitIntoSentences(text).length;
3930
2932
  }
3931
2933
 
3932
2934
  /**
3933
- * @@@
2935
+ * Counts number of words in the text
3934
2936
  *
3935
- * @private internal utility of `createPipelineExecutor`
2937
+ * @public exported from `@promptbook/utils`
3936
2938
  */
3937
- function executeTemplate(options) {
3938
- return __awaiter(this, void 0, void 0, function () {
3939
- 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;
3940
- var e_1, _f, _g;
3941
- return __generator(this, function (_h) {
3942
- switch (_h.label) {
3943
- case 0:
3944
- 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;
3945
- maxExecutionAttempts = settings.maxExecutionAttempts;
3946
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3947
- title = currentTemplate.title;
3948
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3949
- return [4 /*yield*/, onProgress({
3950
- name: name,
3951
- title: title,
3952
- isStarted: false,
3953
- isDone: false,
3954
- templateType: currentTemplate.templateType,
3955
- parameterName: currentTemplate.resultingParameterName,
3956
- parameterValue: null,
3957
- // <- [🍸]
3958
- })];
3959
- case 1:
3960
- _h.sent();
3961
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3962
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3963
- // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3964
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3965
- 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)
3966
- .map(function (name) { return "{".concat(name, "}"); })
3967
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3968
- .map(function (name) { return "{".concat(name, "}"); })
3969
- .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3970
- }
3971
- _b = (_a = Object).freeze;
3972
- _c = [{}];
3973
- return [4 /*yield*/, getReservedParametersForTemplate({
3974
- preparedPipeline: preparedPipeline,
3975
- template: currentTemplate,
3976
- pipelineIdentification: pipelineIdentification,
3977
- })];
3978
- case 2:
3979
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3980
- definedParameterNames = new Set(Object.keys(definedParameters));
3981
- parameters = {};
3982
- _loop_1 = function (parameterName) {
3983
- // Situation: Parameter is defined and used
3984
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3985
- parameters[parameterName] = definedParameters[parameterName];
3986
- }
3987
- // Situation: Parameter is defined but NOT used
3988
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3989
- // Situation: Parameter is NOT defined BUT used
3990
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3991
- // Houston, we have a problem
3992
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3993
- 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 "); }));
3994
- }
3995
- };
3996
- try {
3997
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3998
- // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
3999
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4000
- parameterName = _e.value;
4001
- _loop_1(parameterName);
4002
- }
4003
- }
4004
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4005
- finally {
4006
- try {
4007
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4008
- }
4009
- finally { if (e_1) throw e_1.error; }
4010
- }
4011
- // 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
4012
- Object.freeze(parameters);
4013
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4014
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
4015
- preparedContent = (currentTemplate.preparedContent || '{content}')
4016
- .split('{content}')
4017
- .join(currentTemplate.content);
4018
- return [4 /*yield*/, executeFormatCells({
4019
- jokerParameterNames: jokerParameterNames,
4020
- priority: priority,
4021
- maxAttempts: maxAttempts,
4022
- preparedContent: preparedContent,
4023
- parameters: parameters,
4024
- template: currentTemplate,
4025
- preparedPipeline: preparedPipeline,
4026
- tools: tools,
4027
- llmTools: llmTools,
4028
- settings: settings,
4029
- $executionReport: $executionReport,
4030
- pipelineIdentification: pipelineIdentification,
4031
- })];
4032
- case 3:
4033
- resultString = _h.sent();
4034
- return [4 /*yield*/, onProgress({
4035
- name: name,
4036
- title: title,
4037
- isStarted: true,
4038
- isDone: true,
4039
- templateType: currentTemplate.templateType,
4040
- parameterName: currentTemplate.resultingParameterName,
4041
- parameterValue: resultString,
4042
- // <- [🍸]
4043
- })];
4044
- case 4:
4045
- _h.sent();
4046
- return [2 /*return*/, Object.freeze((_g = {},
4047
- _g[currentTemplate.resultingParameterName] =
4048
- // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4049
- resultString,
4050
- _g))];
4051
- }
4052
- });
4053
- });
2939
+ function countWords(text) {
2940
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2941
+ text = removeDiacritics(text);
2942
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
4054
2943
  }
2944
+
4055
2945
  /**
4056
- * TODO: [🤹‍♂️]
2946
+ * Index of all counter functions
2947
+ *
2948
+ * @public exported from `@promptbook/utils`
4057
2949
  */
2950
+ var CountUtils = {
2951
+ CHARACTERS: countCharacters,
2952
+ WORDS: countWords,
2953
+ SENTENCES: countSentences,
2954
+ PARAGRAPHS: countParagraphs,
2955
+ LINES: countLines,
2956
+ PAGES: countPages,
2957
+ };
4058
2958
 
4059
2959
  /**
4060
- * @@@
2960
+ * Function checkExpectations will check if the expectations on given value are met
4061
2961
  *
4062
- * @private internal utility of `createPipelineExecutor`
2962
+ * Note: There are two simmilar functions:
2963
+ * - `checkExpectations` which throws an error if the expectations are not met
2964
+ * - `isPassingExpectations` which returns a boolean
2965
+ *
2966
+ * @throws {ExpectError} if the expectations are not met
2967
+ * @returns {void} Nothing
2968
+ * @private internal function of `createPipelineExecutor`
4063
2969
  */
4064
- function filterJustOutputParameters(options) {
2970
+ function checkExpectations(expectations, value) {
4065
2971
  var e_1, _a;
4066
- var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4067
- var outputParameters = {};
4068
- var _loop_1 = function (parameter) {
4069
- if (parametersToPass[parameter.name] === undefined) {
4070
- // [4]
4071
- $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 "); })));
4072
- return "continue";
4073
- }
4074
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4075
- };
4076
2972
  try {
4077
- // Note: Filter ONLY output parameters
4078
- // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4079
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4080
- var isOutput = _a.isOutput;
4081
- return isOutput;
4082
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
4083
- var parameter = _c.value;
4084
- _loop_1(parameter);
2973
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
2974
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
2975
+ var amount = CountUtils[unit.toUpperCase()](value);
2976
+ if (min && amount < min) {
2977
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2978
+ } /* not else */
2979
+ if (max && amount > max) {
2980
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2981
+ }
4085
2982
  }
4086
2983
  }
4087
2984
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -4091,27 +2988,600 @@
4091
2988
  }
4092
2989
  finally { if (e_1) throw e_1.error; }
4093
2990
  }
4094
- return outputParameters;
4095
2991
  }
2992
+ /**
2993
+ * TODO: [💝] Unite object for expecting amount and format
2994
+ */
4096
2995
 
4097
2996
  /**
4098
- * @@@
4099
- *
4100
- * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
2997
+ * Creates executor function from pipeline and execution tools.
4101
2998
  *
4102
- * @private internal utility of `createPipelineExecutor`
2999
+ * @returns The executor function
3000
+ * @throws {PipelineLogicError} on logical error in the pipeline
3001
+ * @public exported from `@promptbook/core`
4103
3002
  */
4104
- function executePipeline(options) {
4105
- return __awaiter(this, void 0, void 0, function () {
4106
- 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;
3003
+ function createPipelineExecutor(options) {
3004
+ var _this = this;
3005
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3006
+ 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;
3007
+ validatePipeline(pipeline);
3008
+ var pipelineIdentification = (function () {
3009
+ // Note: This is a 😐 implementation of [🚞]
3010
+ var _ = [];
3011
+ if (pipeline.sourceFile !== undefined) {
3012
+ _.push("File: ".concat(pipeline.sourceFile));
3013
+ }
3014
+ if (pipeline.pipelineUrl !== undefined) {
3015
+ _.push("Url: ".concat(pipeline.pipelineUrl));
3016
+ }
3017
+ return _.join('\n');
3018
+ })();
3019
+ var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3020
+ var preparedPipeline;
3021
+ if (isPipelinePrepared(pipeline)) {
3022
+ preparedPipeline = pipeline;
3023
+ }
3024
+ else if (isNotPreparedWarningSupressed !== true) {
3025
+ 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 "); }));
3026
+ }
3027
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3028
+ // TODO:[main] !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3029
+ function getContextForTemplate(template) {
3030
+ return __awaiter(this, void 0, void 0, function () {
3031
+ return __generator(this, function (_a) {
3032
+ TODO_USE(template);
3033
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3034
+ });
3035
+ });
3036
+ }
3037
+ function getKnowledgeForTemplate(template) {
3038
+ return __awaiter(this, void 0, void 0, function () {
3039
+ return __generator(this, function (_a) {
3040
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3041
+ TODO_USE(template);
3042
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3043
+ var content = _a.content;
3044
+ return "- ".concat(content);
3045
+ }).join('\n')];
3046
+ });
3047
+ });
3048
+ }
3049
+ function getSamplesForTemplate(template) {
3050
+ return __awaiter(this, void 0, void 0, function () {
3051
+ return __generator(this, function (_a) {
3052
+ // TODO: [♨] Implement Better - use real index and keyword search
3053
+ TODO_USE(template);
3054
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3055
+ });
3056
+ });
3057
+ }
3058
+ function getReservedParametersForTemplate(template) {
3059
+ return __awaiter(this, void 0, void 0, function () {
3060
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3061
+ var e_3, _a;
3062
+ return __generator(this, function (_b) {
3063
+ switch (_b.label) {
3064
+ case 0: return [4 /*yield*/, getContextForTemplate(template)];
3065
+ case 1:
3066
+ context = _b.sent();
3067
+ return [4 /*yield*/, getKnowledgeForTemplate(template)];
3068
+ case 2:
3069
+ knowledge = _b.sent();
3070
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3071
+ case 3:
3072
+ samples = _b.sent();
3073
+ currentDate = new Date().toISOString();
3074
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3075
+ reservedParameters = {
3076
+ content: RESERVED_PARAMETER_RESTRICTED,
3077
+ context: context,
3078
+ knowledge: knowledge,
3079
+ samples: samples,
3080
+ currentDate: currentDate,
3081
+ modelName: modelName,
3082
+ };
3083
+ _loop_3 = function (parameterName) {
3084
+ if (reservedParameters[parameterName] === undefined) {
3085
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3086
+ }
3087
+ };
3088
+ try {
3089
+ // Note: Doublecheck that ALL reserved parameters are defined:
3090
+ 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()) {
3091
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3092
+ _loop_3(parameterName);
3093
+ }
3094
+ }
3095
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
3096
+ finally {
3097
+ try {
3098
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3099
+ }
3100
+ finally { if (e_3) throw e_3.error; }
3101
+ }
3102
+ return [2 /*return*/, reservedParameters];
3103
+ }
3104
+ });
3105
+ });
3106
+ }
3107
+ function executeSingleTemplate(currentTemplate) {
3108
+ return __awaiter(this, void 0, void 0, function () {
3109
+ 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;
3110
+ var e_4, _f, _g;
3111
+ return __generator(this, function (_h) {
3112
+ switch (_h.label) {
3113
+ case 0:
3114
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3115
+ title = currentTemplate.title;
3116
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3117
+ if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3118
+ progress_1 = {
3119
+ name: name,
3120
+ title: title,
3121
+ isStarted: false,
3122
+ isDone: false,
3123
+ templateType: currentTemplate.templateType,
3124
+ parameterName: currentTemplate.resultingParameterName,
3125
+ parameterValue: null,
3126
+ // <- [3]
3127
+ };
3128
+ if (isReturned) {
3129
+ 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)
3130
+ .split('\n')
3131
+ .map(function (line) { return "> ".concat(line); })
3132
+ .join('\n')), "\n "); }));
3133
+ }
3134
+ return [4 /*yield*/, onProgress(progress_1)];
3135
+ case 1:
3136
+ _h.sent();
3137
+ _h.label = 2;
3138
+ case 2:
3139
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3140
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3141
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3142
+ 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)
3143
+ .map(function (name) { return "{".concat(name, "}"); })
3144
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3145
+ .map(function (name) { return "{".concat(name, "}"); })
3146
+ .join(', '), "\n\n "); }));
3147
+ }
3148
+ _b = (_a = Object).freeze;
3149
+ _c = [{}];
3150
+ return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3151
+ case 3:
3152
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3153
+ definedParameterNames = new Set(Object.keys(definedParameters));
3154
+ parameters = {};
3155
+ _loop_4 = function (parameterName) {
3156
+ // Situation: Parameter is defined and used
3157
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3158
+ parameters[parameterName] = definedParameters[parameterName];
3159
+ }
3160
+ // Situation: Parameter is defined but NOT used
3161
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3162
+ // Situation: Parameter is NOT defined BUT used
3163
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3164
+ // Houston, we have a problem
3165
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3166
+ 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 "); }));
3167
+ }
3168
+ };
3169
+ try {
3170
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3171
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3172
+ parameterName = _e.value;
3173
+ _loop_4(parameterName);
3174
+ }
3175
+ }
3176
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
3177
+ finally {
3178
+ try {
3179
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3180
+ }
3181
+ finally { if (e_4) throw e_4.error; }
3182
+ }
3183
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3184
+ Object.freeze(parameters);
3185
+ result = null;
3186
+ resultString = null;
3187
+ expectError = null;
3188
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3189
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3190
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3191
+ .split('{content}')
3192
+ .join(currentTemplate.content);
3193
+ _loop_5 = function (attempt) {
3194
+ 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;
3195
+ var e_5, _s, e_7, _t, e_6, _u;
3196
+ return __generator(this, function (_v) {
3197
+ switch (_v.label) {
3198
+ case 0:
3199
+ isJokerAttempt = attempt < 0;
3200
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3201
+ if (isJokerAttempt && !jokerParameterName) {
3202
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3203
+ }
3204
+ result = null;
3205
+ resultString = null;
3206
+ expectError = null;
3207
+ if (isJokerAttempt) {
3208
+ if (parameters[jokerParameterName] === undefined) {
3209
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3210
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3211
+ }
3212
+ else {
3213
+ resultString = parameters[jokerParameterName];
3214
+ }
3215
+ }
3216
+ _v.label = 1;
3217
+ case 1:
3218
+ _v.trys.push([1, 44, 45, 46]);
3219
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3220
+ _j = currentTemplate.templateType;
3221
+ switch (_j) {
3222
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3223
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3224
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3225
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3226
+ }
3227
+ return [3 /*break*/, 25];
3228
+ case 2:
3229
+ resultString = replaceParameters(preparedContent, parameters);
3230
+ return [3 /*break*/, 26];
3231
+ case 3:
3232
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3233
+ prompt = {
3234
+ title: currentTemplate.title,
3235
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3236
+ ? preparedPipeline.pipelineUrl
3237
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3238
+ parameters: parameters,
3239
+ content: preparedContent,
3240
+ modelRequirements: modelRequirements,
3241
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3242
+ var name = _a.name;
3243
+ return name === currentTemplate.personaName;
3244
+ }) || {})), currentTemplate.expectations),
3245
+ format: currentTemplate.format,
3246
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3247
+ }; // <- TODO: Not very good type guard
3248
+ _k = modelRequirements.modelVariant;
3249
+ switch (_k) {
3250
+ case 'CHAT': return [3 /*break*/, 4];
3251
+ case 'COMPLETION': return [3 /*break*/, 6];
3252
+ case 'EMBEDDING': return [3 /*break*/, 8];
3253
+ }
3254
+ return [3 /*break*/, 10];
3255
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3256
+ case 5:
3257
+ chatResult = _v.sent();
3258
+ // TODO: [🍬] Destroy chatThread
3259
+ result = chatResult;
3260
+ resultString = chatResult.content;
3261
+ return [3 /*break*/, 11];
3262
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3263
+ case 7:
3264
+ completionResult = _v.sent();
3265
+ result = completionResult;
3266
+ resultString = completionResult.content;
3267
+ return [3 /*break*/, 11];
3268
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3269
+ case 9:
3270
+ embeddingResult = _v.sent();
3271
+ result = embeddingResult;
3272
+ resultString = embeddingResult.content.join(',');
3273
+ return [3 /*break*/, 11];
3274
+ case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3275
+ .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3276
+ case 11: return [3 /*break*/, 26];
3277
+ case 12:
3278
+ if (arrayableToArray(tools.script).length === 0) {
3279
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3280
+ }
3281
+ if (!currentTemplate.contentLanguage) {
3282
+ 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 "); }));
3283
+ }
3284
+ // TODO: DRY [1]
3285
+ scriptPipelineExecutionErrors = [];
3286
+ _v.label = 13;
3287
+ case 13:
3288
+ _v.trys.push([13, 20, 21, 22]);
3289
+ _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3290
+ _v.label = 14;
3291
+ case 14:
3292
+ if (!!_m.done) return [3 /*break*/, 19];
3293
+ scriptTools = _m.value;
3294
+ _v.label = 15;
3295
+ case 15:
3296
+ _v.trys.push([15, 17, , 18]);
3297
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3298
+ scriptLanguage: currentTemplate.contentLanguage,
3299
+ script: preparedContent,
3300
+ parameters: parameters,
3301
+ }))];
3302
+ case 16:
3303
+ resultString = _v.sent();
3304
+ return [3 /*break*/, 19];
3305
+ case 17:
3306
+ error_2 = _v.sent();
3307
+ if (!(error_2 instanceof Error)) {
3308
+ throw error_2;
3309
+ }
3310
+ if (error_2 instanceof UnexpectedError) {
3311
+ throw error_2;
3312
+ }
3313
+ scriptPipelineExecutionErrors.push(error_2);
3314
+ return [3 /*break*/, 18];
3315
+ case 18:
3316
+ _m = _l.next();
3317
+ return [3 /*break*/, 14];
3318
+ case 19: return [3 /*break*/, 22];
3319
+ case 20:
3320
+ e_5_1 = _v.sent();
3321
+ e_5 = { error: e_5_1 };
3322
+ return [3 /*break*/, 22];
3323
+ case 21:
3324
+ try {
3325
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3326
+ }
3327
+ finally { if (e_5) throw e_5.error; }
3328
+ return [7 /*endfinally*/];
3329
+ case 22:
3330
+ if (resultString !== null) {
3331
+ return [3 /*break*/, 26];
3332
+ }
3333
+ if (scriptPipelineExecutionErrors.length === 1) {
3334
+ throw scriptPipelineExecutionErrors[0];
3335
+ }
3336
+ else {
3337
+ 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
3338
+ .map(function (error) { return '- ' + error.message; })
3339
+ .join('\n\n')), "\n "); }));
3340
+ }
3341
+ case 23:
3342
+ if (tools.userInterface === undefined) {
3343
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3344
+ }
3345
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3346
+ promptTitle: currentTemplate.title,
3347
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3348
+ defaultValue: replaceParameters(preparedContent, parameters),
3349
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3350
+ placeholder: undefined,
3351
+ priority: priority,
3352
+ }))];
3353
+ case 24:
3354
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3355
+ resultString = _v.sent();
3356
+ return [3 /*break*/, 26];
3357
+ case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3358
+ case 26:
3359
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3360
+ _v.label = 27;
3361
+ case 27:
3362
+ _v.trys.push([27, 41, 42, 43]);
3363
+ _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3364
+ _v.label = 28;
3365
+ case 28:
3366
+ if (!!_p.done) return [3 /*break*/, 40];
3367
+ functionName = _p.value;
3368
+ // TODO: DRY [1]
3369
+ scriptPipelineExecutionErrors = [];
3370
+ postprocessingError = null;
3371
+ _v.label = 29;
3372
+ case 29:
3373
+ _v.trys.push([29, 36, 37, 38]);
3374
+ _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3375
+ _v.label = 30;
3376
+ case 30:
3377
+ if (!!_r.done) return [3 /*break*/, 35];
3378
+ scriptTools = _r.value;
3379
+ _v.label = 31;
3380
+ case 31:
3381
+ _v.trys.push([31, 33, , 34]);
3382
+ return [4 /*yield*/, scriptTools.execute({
3383
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3384
+ script: "".concat(functionName, "(resultString)"),
3385
+ parameters: {
3386
+ resultString: resultString || '',
3387
+ // Note: No ...parametersForTemplate, because working with result only
3388
+ },
3389
+ })];
3390
+ case 32:
3391
+ resultString = _v.sent();
3392
+ postprocessingError = null;
3393
+ return [3 /*break*/, 35];
3394
+ case 33:
3395
+ error_3 = _v.sent();
3396
+ if (!(error_3 instanceof Error)) {
3397
+ throw error_3;
3398
+ }
3399
+ if (error_3 instanceof UnexpectedError) {
3400
+ throw error_3;
3401
+ }
3402
+ postprocessingError = error_3;
3403
+ scriptPipelineExecutionErrors.push(error_3);
3404
+ return [3 /*break*/, 34];
3405
+ case 34:
3406
+ _r = _q.next();
3407
+ return [3 /*break*/, 30];
3408
+ case 35: return [3 /*break*/, 38];
3409
+ case 36:
3410
+ e_6_1 = _v.sent();
3411
+ e_6 = { error: e_6_1 };
3412
+ return [3 /*break*/, 38];
3413
+ case 37:
3414
+ try {
3415
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3416
+ }
3417
+ finally { if (e_6) throw e_6.error; }
3418
+ return [7 /*endfinally*/];
3419
+ case 38:
3420
+ if (postprocessingError) {
3421
+ throw postprocessingError;
3422
+ }
3423
+ _v.label = 39;
3424
+ case 39:
3425
+ _p = _o.next();
3426
+ return [3 /*break*/, 28];
3427
+ case 40: return [3 /*break*/, 43];
3428
+ case 41:
3429
+ e_7_1 = _v.sent();
3430
+ e_7 = { error: e_7_1 };
3431
+ return [3 /*break*/, 43];
3432
+ case 42:
3433
+ try {
3434
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3435
+ }
3436
+ finally { if (e_7) throw e_7.error; }
3437
+ return [7 /*endfinally*/];
3438
+ case 43:
3439
+ // TODO: [💝] Unite object for expecting amount and format
3440
+ if (currentTemplate.format) {
3441
+ if (currentTemplate.format === 'JSON') {
3442
+ if (!isValidJsonString(resultString || '')) {
3443
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3444
+ try {
3445
+ resultString = extractJsonBlock(resultString || '');
3446
+ }
3447
+ catch (error) {
3448
+ keepUnused(error);
3449
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3450
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3451
+ }
3452
+ }
3453
+ }
3454
+ else {
3455
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3456
+ }
3457
+ }
3458
+ // TODO: [💝] Unite object for expecting amount and format
3459
+ if (currentTemplate.expectations) {
3460
+ checkExpectations(currentTemplate.expectations, resultString || '');
3461
+ }
3462
+ return [2 /*return*/, "break-attempts"];
3463
+ case 44:
3464
+ error_4 = _v.sent();
3465
+ if (!(error_4 instanceof ExpectError)) {
3466
+ throw error_4;
3467
+ }
3468
+ expectError = error_4;
3469
+ return [3 /*break*/, 46];
3470
+ case 45:
3471
+ if (!isJokerAttempt &&
3472
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3473
+ prompt
3474
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3475
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3476
+ ) {
3477
+ // TODO: [🧠] Maybe put other templateTypes into report
3478
+ executionReport.promptExecutions.push({
3479
+ prompt: __assign({}, prompt),
3480
+ result: result || undefined,
3481
+ error: expectError === null ? undefined : serializeError(expectError),
3482
+ });
3483
+ }
3484
+ return [7 /*endfinally*/];
3485
+ case 46:
3486
+ if (expectError !== null && attempt === maxAttempts - 1) {
3487
+ 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
3488
+ .split('\n')
3489
+ .map(function (line) { return "> ".concat(line); })
3490
+ .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) || '')
3491
+ .split('\n')
3492
+ .map(function (line) { return "> ".concat(line); })
3493
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3494
+ ? 'null'
3495
+ : resultString
3496
+ .split('\n')
3497
+ .map(function (line) { return "> ".concat(line); })
3498
+ .join('\n')), "\n ---\n "); }));
3499
+ }
3500
+ return [2 /*return*/];
3501
+ }
3502
+ });
3503
+ };
3504
+ attempt = -jokerParameterNames.length;
3505
+ _h.label = 4;
3506
+ case 4:
3507
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3508
+ return [5 /*yield**/, _loop_5(attempt)];
3509
+ case 5:
3510
+ state_2 = _h.sent();
3511
+ switch (state_2) {
3512
+ case "break-attempts": return [3 /*break*/, 7];
3513
+ }
3514
+ _h.label = 6;
3515
+ case 6:
3516
+ attempt++;
3517
+ return [3 /*break*/, 4];
3518
+ case 7:
3519
+ if (resultString === null) {
3520
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3521
+ }
3522
+ if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3523
+ progress_2 = {
3524
+ name: name,
3525
+ title: title,
3526
+ isStarted: true,
3527
+ isDone: true,
3528
+ templateType: currentTemplate.templateType,
3529
+ parameterName: currentTemplate.resultingParameterName,
3530
+ parameterValue: resultString,
3531
+ // <- [3]
3532
+ };
3533
+ if (isReturned) {
3534
+ 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)
3535
+ .split('\n')
3536
+ .map(function (line) { return "> ".concat(line); })
3537
+ .join('\n')), "\n\n "); }));
3538
+ }
3539
+ return [4 /*yield*/, onProgress(progress_2)];
3540
+ case 8:
3541
+ _h.sent();
3542
+ _h.label = 9;
3543
+ case 9:
3544
+ 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)));
3545
+ return [2 /*return*/];
3546
+ }
3547
+ });
3548
+ });
3549
+ }
3550
+ function filterJustOutputParameters() {
3551
+ var e_8, _a;
3552
+ var outputParameters = {};
3553
+ var _loop_6 = function (parameter) {
3554
+ if (parametersToPass[parameter.name] === undefined) {
3555
+ // [4]
3556
+ 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 "); })));
3557
+ return "continue";
3558
+ }
3559
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3560
+ };
3561
+ try {
3562
+ // Note: Filter ONLY output parameters
3563
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3564
+ var isOutput = _a.isOutput;
3565
+ return isOutput;
3566
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3567
+ var parameter = _c.value;
3568
+ _loop_6(parameter);
3569
+ }
3570
+ }
3571
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
3572
+ finally {
3573
+ try {
3574
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3575
+ }
3576
+ finally { if (e_8) throw e_8.error; }
3577
+ }
3578
+ return outputParameters;
3579
+ }
3580
+ 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;
4107
3581
  var e_1, _e, e_2, _f;
4108
3582
  return __generator(this, function (_g) {
4109
3583
  switch (_g.label) {
4110
3584
  case 0:
4111
- inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4112
- maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4113
- preparedPipeline = options.preparedPipeline;
4114
- llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
4115
3585
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
4116
3586
  return [4 /*yield*/, preparePipeline(pipeline, {
4117
3587
  llmTools: llmTools,
@@ -4120,7 +3590,6 @@
4120
3590
  })];
4121
3591
  case 1:
4122
3592
  preparedPipeline = _g.sent();
4123
- setPreparedPipeline(preparedPipeline);
4124
3593
  _g.label = 2;
4125
3594
  case 2:
4126
3595
  errors = [];
@@ -4190,7 +3659,7 @@
4190
3659
  return name === parameterName;
4191
3660
  });
4192
3661
  if (!(parameter === undefined)) return [3 /*break*/, 1];
4193
- 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 "); })));
3662
+ 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 "); })));
4194
3663
  return [3 /*break*/, 4];
4195
3664
  case 1:
4196
3665
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -4202,10 +3671,10 @@
4202
3671
  // Note: Wait a short time to prevent race conditions
4203
3672
  _h.sent();
4204
3673
  _h.label = 3;
4205
- 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 "); }), {
3674
+ 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 "); }), {
4206
3675
  isSuccessful: false,
4207
3676
  errors: __spreadArray([
4208
- 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 "); }))
3677
+ 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 "); }))
4209
3678
  ], __read(errors), false).map(serializeError),
4210
3679
  warnings: warnings.map(serializeError),
4211
3680
  executionReport: executionReport,
@@ -4269,7 +3738,7 @@
4269
3738
  case 0:
4270
3739
  if (loopLimit-- < 0) {
4271
3740
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4272
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3741
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4273
3742
  }
4274
3743
  currentTemplate = unresovedTemplates_1.find(function (template) {
4275
3744
  return template.dependentParameterNames.every(function (name) {
@@ -4279,52 +3748,29 @@
4279
3748
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4280
3749
  throw new UnexpectedError(
4281
3750
  // TODO: [🐎] DRY
4282
- 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
3751
+ 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
4283
3752
  .map(function (_a) {
4284
3753
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4285
3754
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4286
3755
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4287
3756
  .join(' and '));
4288
3757
  })
4289
- .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 "); }));
3758
+ .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 "); }));
4290
3759
  case 1:
4291
3760
  if (!!currentTemplate) return [3 /*break*/, 3];
4292
- /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3761
+ /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4293
3762
  case 2:
4294
- /* [🤹‍♂️] */ _j.sent();
3763
+ /* [5] */ _j.sent();
4295
3764
  return [3 /*break*/, 4];
4296
3765
  case 3:
4297
3766
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4298
- work_1 = executeTemplate({
4299
- currentTemplate: currentTemplate,
4300
- preparedPipeline: preparedPipeline,
4301
- parametersToPass: parametersToPass,
4302
- tools: tools,
4303
- llmTools: llmTools,
4304
- onProgress: function (progress) {
4305
- if (isReturned) {
4306
- 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)
4307
- .split('\n')
4308
- .map(function (line) { return "> ".concat(line); })
4309
- .join('\n')), "\n "); }));
4310
- }
4311
- if (onProgress) {
4312
- onProgress(progress);
4313
- }
4314
- },
4315
- settings: settings,
4316
- $executionReport: executionReport,
4317
- pipelineIdentification: pipelineIdentification,
4318
- })
4319
- .then(function (newParametersToPass) {
4320
- parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3767
+ work_1 = executeSingleTemplate(currentTemplate)
3768
+ .then(function () {
4321
3769
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4322
3770
  })
4323
3771
  .then(function () {
4324
3772
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4325
3773
  });
4326
- // <- Note: Errors are catched here [3]
4327
- // 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
4328
3774
  resolving_1.push(work_1);
4329
3775
  _j.label = 4;
4330
3776
  case 4: return [2 /*return*/];
@@ -4351,12 +3797,7 @@
4351
3797
  var result = _a.result;
4352
3798
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4353
3799
  })), false));
4354
- outputParameters_1 = filterJustOutputParameters({
4355
- preparedPipeline: preparedPipeline,
4356
- parametersToPass: parametersToPass,
4357
- $warnings: warnings,
4358
- pipelineIdentification: pipelineIdentification,
4359
- });
3800
+ outputParameters_1 = filterJustOutputParameters();
4360
3801
  isReturned = true;
4361
3802
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4362
3803
  // Note: Wait a short time to prevent race conditions
@@ -4379,12 +3820,7 @@
4379
3820
  var result = _a.result;
4380
3821
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4381
3822
  })), false));
4382
- outputParameters = filterJustOutputParameters({
4383
- preparedPipeline: preparedPipeline,
4384
- parametersToPass: parametersToPass,
4385
- $warnings: warnings,
4386
- pipelineIdentification: pipelineIdentification,
4387
- });
3823
+ outputParameters = filterJustOutputParameters();
4388
3824
  isReturned = true;
4389
3825
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4390
3826
  // Note: Wait a short time to prevent race conditions
@@ -4404,63 +3840,22 @@
4404
3840
  })];
4405
3841
  }
4406
3842
  });
4407
- });
4408
- }
4409
-
4410
- /**
4411
- * Creates executor function from pipeline and execution tools.
4412
- *
4413
- * @returns The executor function
4414
- * @throws {PipelineLogicError} on logical error in the pipeline
4415
- * @public exported from `@promptbook/core`
4416
- */
4417
- function createPipelineExecutor(options) {
4418
- var _this = this;
4419
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4420
- 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;
4421
- validatePipeline(pipeline);
4422
- var pipelineIdentification = (function () {
4423
- // Note: This is a 😐 implementation of [🚞]
4424
- var _ = [];
4425
- if (pipeline.sourceFile !== undefined) {
4426
- _.push("File: ".concat(pipeline.sourceFile));
4427
- }
4428
- if (pipeline.pipelineUrl !== undefined) {
4429
- _.push("Url: ".concat(pipeline.pipelineUrl));
4430
- }
4431
- return _.join('\n');
4432
- })();
4433
- var preparedPipeline;
4434
- if (isPipelinePrepared(pipeline)) {
4435
- preparedPipeline = pipeline;
4436
- }
4437
- else if (isNotPreparedWarningSupressed !== true) {
4438
- 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 "); }));
4439
- }
4440
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4441
- return __generator(this, function (_a) {
4442
- return [2 /*return*/, executePipeline({
4443
- pipeline: pipeline,
4444
- preparedPipeline: preparedPipeline,
4445
- setPreparedPipeline: function (newPreparedPipeline) {
4446
- preparedPipeline = newPreparedPipeline;
4447
- },
4448
- inputParameters: inputParameters,
4449
- tools: tools,
4450
- onProgress: onProgress,
4451
- pipelineIdentification: pipelineIdentification,
4452
- settings: {
4453
- maxExecutionAttempts: maxExecutionAttempts,
4454
- maxParallelCount: maxParallelCount,
4455
- csvSettings: csvSettings,
4456
- isVerbose: isVerbose,
4457
- isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4458
- },
4459
- })];
4460
- });
4461
3843
  }); };
4462
3844
  return pipelineExecutor;
4463
3845
  }
3846
+ /**
3847
+ * TODO:[main] !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3848
+ * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3849
+ * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3850
+ * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3851
+ * TODO: [♈] Probbably move expectations from templates to parameters
3852
+ * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
3853
+ * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
3854
+ * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
3855
+ * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3856
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3857
+ * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
3858
+ */
4464
3859
 
4465
3860
  /**
4466
3861
  * @@@
@@ -4570,13 +3965,8 @@
4570
3965
  case 6: return [3 /*break*/, 8];
4571
3966
  case 7:
4572
3967
  error_1 = _c.sent();
4573
- // Note: Here is expected error:
4574
- // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4575
- if (!(error_1 instanceof PipelineExecutionError)) {
4576
- throw error_1;
4577
- }
4578
3968
  // TODO: [🟥] Detect browser / node and make it colorfull
4579
- console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
3969
+ console.error(error_1);
4580
3970
  return [3 /*break*/, 8];
4581
3971
  case 8: return [2 /*return*/, {
4582
3972
  name: name,
@@ -4621,7 +4011,7 @@
4621
4011
  var partialPieces, pieces;
4622
4012
  return __generator(this, function (_a) {
4623
4013
  switch (_a.label) {
4624
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4014
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝][main] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4625
4015
  options)];
4626
4016
  case 1:
4627
4017
  partialPieces = _a.sent();
@@ -5549,241 +4939,6 @@
5549
4939
  },
5550
4940
  };
5551
4941
 
5552
- /**
5553
- * @@@
5554
- *
5555
- * @param text @@@
5556
- * @returns @@@
5557
- * @example 'HELLO_WORLD'
5558
- * @example 'I_LOVE_PROMPTBOOK'
5559
- * @public exported from `@promptbook/utils`
5560
- */
5561
- function normalizeTo_SCREAMING_CASE(text) {
5562
- var e_1, _a;
5563
- var charType;
5564
- var lastCharType = 'OTHER';
5565
- var normalizedName = '';
5566
- try {
5567
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5568
- var char = text_1_1.value;
5569
- var normalizedChar = void 0;
5570
- if (/^[a-z]$/.test(char)) {
5571
- charType = 'LOWERCASE';
5572
- normalizedChar = char.toUpperCase();
5573
- }
5574
- else if (/^[A-Z]$/.test(char)) {
5575
- charType = 'UPPERCASE';
5576
- normalizedChar = char;
5577
- }
5578
- else if (/^[0-9]$/.test(char)) {
5579
- charType = 'NUMBER';
5580
- normalizedChar = char;
5581
- }
5582
- else if (/^\/$/.test(char)) {
5583
- charType = 'SLASH';
5584
- normalizedChar = char;
5585
- }
5586
- else {
5587
- charType = 'OTHER';
5588
- normalizedChar = '_';
5589
- }
5590
- if (charType !== lastCharType &&
5591
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
5592
- !(lastCharType === 'NUMBER') &&
5593
- !(charType === 'NUMBER')) {
5594
- normalizedName += '_';
5595
- }
5596
- normalizedName += normalizedChar;
5597
- lastCharType = charType;
5598
- }
5599
- }
5600
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5601
- finally {
5602
- try {
5603
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5604
- }
5605
- finally { if (e_1) throw e_1.error; }
5606
- }
5607
- normalizedName = normalizedName.replace(/_+/g, '_');
5608
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
5609
- normalizedName = normalizedName.replace(/^_/, '');
5610
- normalizedName = normalizedName.replace(/_$/, '');
5611
- return normalizedName;
5612
- }
5613
- /**
5614
- * TODO: Tests
5615
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
5616
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
5617
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
5618
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
5619
- * TODO: [🌺] Use some intermediate util splitWords
5620
- */
5621
-
5622
- /**
5623
- * @@@
5624
- *
5625
- * @param text @@@
5626
- * @param _isFirstLetterCapital @@@
5627
- * @returns @@@
5628
- * @example 'helloWorld'
5629
- * @example 'iLovePromptbook'
5630
- * @public exported from `@promptbook/utils`
5631
- */
5632
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5633
- var e_1, _a;
5634
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5635
- var charType;
5636
- var lastCharType = null;
5637
- var normalizedName = '';
5638
- try {
5639
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5640
- var char = text_1_1.value;
5641
- var normalizedChar = void 0;
5642
- if (/^[a-z]$/.test(char)) {
5643
- charType = 'LOWERCASE';
5644
- normalizedChar = char;
5645
- }
5646
- else if (/^[A-Z]$/.test(char)) {
5647
- charType = 'UPPERCASE';
5648
- normalizedChar = char.toLowerCase();
5649
- }
5650
- else if (/^[0-9]$/.test(char)) {
5651
- charType = 'NUMBER';
5652
- normalizedChar = char;
5653
- }
5654
- else {
5655
- charType = 'OTHER';
5656
- normalizedChar = '';
5657
- }
5658
- if (!lastCharType) {
5659
- if (_isFirstLetterCapital) {
5660
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5661
- }
5662
- }
5663
- else if (charType !== lastCharType &&
5664
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5665
- !(lastCharType === 'NUMBER') &&
5666
- !(charType === 'NUMBER')) {
5667
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5668
- }
5669
- normalizedName += normalizedChar;
5670
- lastCharType = charType;
5671
- }
5672
- }
5673
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5674
- finally {
5675
- try {
5676
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5677
- }
5678
- finally { if (e_1) throw e_1.error; }
5679
- }
5680
- return normalizedName;
5681
- }
5682
- /**
5683
- * TODO: [🌺] Use some intermediate util splitWords
5684
- */
5685
-
5686
- /**
5687
- * Removes quotes from a string
5688
- *
5689
- * Tip: This is very usefull for post-processing of the result of the LLM model
5690
- * Note: This function removes only the same quotes from the beginning and the end of the string
5691
- * Note: There are two simmilar functions:
5692
- * - `removeQuotes` which removes only bounding quotes
5693
- * - `unwrapResult` which removes whole introduce sentence
5694
- *
5695
- * @param text optionally quoted text
5696
- * @returns text without quotes
5697
- * @public exported from `@promptbook/utils`
5698
- */
5699
- function removeQuotes(text) {
5700
- if (text.startsWith('"') && text.endsWith('"')) {
5701
- return text.slice(1, -1);
5702
- }
5703
- if (text.startsWith('\'') && text.endsWith('\'')) {
5704
- return text.slice(1, -1);
5705
- }
5706
- return text;
5707
- }
5708
-
5709
- /**
5710
- * Function `validateParameterName` will @@@
5711
- *
5712
- * @param parameterName @@@
5713
- * @returns @@@
5714
- * @throws {ParseError} @@@
5715
- * @private within the repository
5716
- */
5717
- function validateParameterName(parameterName) {
5718
- var e_1, _a;
5719
- var rawParameterName = parameterName;
5720
- try {
5721
- for (var _b = __values([
5722
- ['`', '`'],
5723
- ['{', '}'],
5724
- ['[', ']'],
5725
- ['(', ')'],
5726
- ['<', '>'],
5727
- ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5728
- var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5729
- if (parameterName.substring(0, 1) === start &&
5730
- parameterName.substring(parameterName.length - 1, parameterName.length) === end
5731
- // <- TODO: More universal that 1 character
5732
- ) {
5733
- parameterName = parameterName.substring(1, parameterName.length - 1);
5734
- // <- TODO: More universal that 1 character
5735
- }
5736
- }
5737
- }
5738
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5739
- finally {
5740
- try {
5741
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5742
- }
5743
- finally { if (e_1) throw e_1.error; }
5744
- }
5745
- // TODO: [🐠] Following try-catch block should be part of common validators logic
5746
- try {
5747
- /*
5748
- Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5749
- if (parameterName.includes(' ')) {
5750
- throw new ParseError(`Parameter name cannot contain spaces`);
5751
- }
5752
- */
5753
- if (parameterName.includes('.')) {
5754
- throw new ParseError("Parameter name cannot contain dots");
5755
- }
5756
- if (parameterName.includes('/') || parameterName.includes('\\')) {
5757
- throw new ParseError("Parameter name cannot contain slashes");
5758
- }
5759
- if (parameterName.includes('(') ||
5760
- parameterName.includes(')') ||
5761
- parameterName.includes('{') ||
5762
- parameterName.includes('}') ||
5763
- parameterName.includes('[') ||
5764
- parameterName.includes(']')) {
5765
- throw new ParseError("Parameter name cannot contain braces");
5766
- }
5767
- parameterName = removeDiacritics(parameterName);
5768
- parameterName = removeEmojis(parameterName);
5769
- parameterName = removeQuotes(parameterName);
5770
- parameterName = normalizeTo_camelCase(parameterName);
5771
- if (parameterName === '') {
5772
- throw new ParseError("Parameter name cannot be empty");
5773
- }
5774
- if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5775
- throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5776
- }
5777
- }
5778
- catch (error) {
5779
- if (!(error instanceof ParseError)) {
5780
- throw error;
5781
- }
5782
- 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 "); }));
5783
- }
5784
- return parameterName;
5785
- }
5786
-
5787
4942
  /**
5788
4943
  * Parses the foreach command
5789
4944
  *
@@ -5813,61 +4968,25 @@
5813
4968
  /**
5814
4969
  * Link to discussion
5815
4970
  */
5816
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
4971
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5817
4972
  /**
5818
4973
  * Example usages of the FOREACH command
5819
4974
  */
5820
4975
  examples: [
5821
- 'FOREACH Text Line `{customers}` -> `{customer}`',
5822
- 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
5823
- 'EACH Csv Cell `{customers}` -> `{subformat}`',
4976
+ 'FOREACH List Line -> `{customer}`',
4977
+ 'FOR List Line -> `{customer}`',
4978
+ 'EACH List Line -> `{customer}`',
4979
+ // <- TODO: [🍭] More
5824
4980
  ],
5825
4981
  /**
5826
4982
  * Parses the FOREACH command
5827
4983
  */
5828
4984
  parse: function (input) {
5829
4985
  var args = input.args;
5830
- var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5831
- var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5832
- var parameterNameArg = args[2] || '';
5833
- var assignSign = args[3];
5834
- var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5835
- return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5836
- });
5837
- if (formatDefinition === undefined) {
5838
- 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; })
5839
- .map(function (formatName) { return "- ".concat(formatName); })
5840
- .join('\n')), "\n "); }));
5841
- // <- TODO: [🏢] List all supported format names
5842
- }
5843
- var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5844
- return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5845
- });
5846
- if (subvalueDefinition === undefined) {
5847
- 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
5848
- .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
5849
- .map(function (subvalueName) { return "- ".concat(subvalueName); })
5850
- .join('\n')), "\n "); }));
5851
- // <- TODO: [🏢] List all supported subformat names for the format
5852
- }
5853
- if (assignSign !== '->') {
5854
- throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
5855
- }
5856
- var parameterName = validateParameterName(parameterNameArg);
5857
- var subparameterNames = args
5858
- .slice(4)
5859
- .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
5860
- .filter(function (parameterName) { return parameterName !== ''; })
5861
- .map(validateParameterName);
5862
- if (subparameterNames.length === 0) {
5863
- throw new ParseError("FOREACH command must have at least one subparameter");
5864
- }
4986
+ keepUnused(args);
4987
+ // <- TODO: [🍭] Implement
5865
4988
  return {
5866
4989
  type: 'FOREACH',
5867
- formatName: formatName,
5868
- subformatName: subformatName,
5869
- parameterName: parameterName,
5870
- subparameterNames: subparameterNames,
5871
4990
  };
5872
4991
  },
5873
4992
  /**
@@ -5876,12 +4995,8 @@
5876
4995
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5877
4996
  */
5878
4997
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5879
- var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
5880
- // TODO: [🍭] Detect double use
5881
- // TODO: [🍭] Detect usage with JOKER and don't allow it
5882
- $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
5883
- keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5884
- // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
4998
+ keepUnused(command, $templateJson, $pipelineJson);
4999
+ // <- TODO: [🍭] Implement
5885
5000
  },
5886
5001
  /**
5887
5002
  * Converts the FOREACH command back to string
@@ -5890,7 +5005,8 @@
5890
5005
  */
5891
5006
  stringify: function (command) {
5892
5007
  keepUnused(command);
5893
- return "---"; // <- TODO: [🛋] Implement
5008
+ return "";
5009
+ // <- TODO: [🍭] Implement
5894
5010
  },
5895
5011
  /**
5896
5012
  * Reads the FOREACH command from the `TemplateJson`
@@ -5899,11 +5015,12 @@
5899
5015
  */
5900
5016
  takeFromTemplateJson: function ($templateJson) {
5901
5017
  keepUnused($templateJson);
5902
- throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5018
+ return [];
5019
+ // <- TODO: [🍭] Implement
5903
5020
  },
5904
5021
  };
5905
5022
  /**
5906
- * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5023
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
5907
5024
  */
5908
5025
 
5909
5026
  /**
@@ -6013,11 +5130,11 @@
6013
5130
  */
6014
5131
  parse: function (input) {
6015
5132
  var args = input.args;
6016
- if (args.length !== 1) {
6017
- throw new ParseError("JOKE command expects exactly one parameter name");
5133
+ var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5134
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5135
+ throw new ParseError("Invalid joker");
6018
5136
  }
6019
- var parameterNameArg = args[0] || '';
6020
- var parameterName = validateParameterName(parameterNameArg);
5137
+ var parameterName = parametersMatch.groups.parameterName;
6021
5138
  return {
6022
5139
  type: 'JOKER',
6023
5140
  parameterName: parameterName,
@@ -6092,9 +5209,6 @@
6092
5209
  */
6093
5210
  parse: function (input) {
6094
5211
  var args = input.args, normalized = input.normalized;
6095
- var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6096
- return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6097
- }).join('\n')), "\n "); });
6098
5212
  // TODO: Make this more elegant and dynamically
6099
5213
  if (normalized.startsWith('MODEL_VARIANT')) {
6100
5214
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -6110,13 +5224,17 @@
6110
5224
  key: 'modelVariant',
6111
5225
  value: 'COMPLETION',
6112
5226
  };
6113
- // <- Note: [🤖]
6114
5227
  }
6115
5228
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
6116
- spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5229
+ return {
5230
+ type: 'MODEL',
5231
+ key: 'modelVariant',
5232
+ value: 'EMBEDDING',
5233
+ };
5234
+ // <- Note: [🤖]
6117
5235
  }
6118
5236
  else {
6119
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5237
+ 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 "); }));
6120
5238
  }
6121
5239
  }
6122
5240
  if (normalized.startsWith('MODEL_NAME')) {
@@ -6141,7 +5259,6 @@
6141
5259
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
6142
5260
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
6143
5261
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6144
- // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
6145
5262
  }
6146
5263
  else {
6147
5264
  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 ")));
@@ -6241,13 +5358,14 @@
6241
5358
  * Parses the PARAMETER command
6242
5359
  */
6243
5360
  parse: function (input) {
6244
- var normalized = input.normalized, args = input.args, raw = input.raw;
6245
- var parameterNameRaw = args.shift() || '';
6246
- var parameterDescriptionRaw = args.join(' ');
6247
- // <- TODO: When [🥶] fixed, change to:
6248
- // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6249
- if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6250
- 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 "); }));
5361
+ var normalized = input.normalized, raw = input.raw;
5362
+ var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5363
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5364
+ throw new ParseError("Invalid parameter");
5365
+ }
5366
+ var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5367
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5368
+ throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6251
5369
  }
6252
5370
  var isInput = normalized.startsWith('INPUT');
6253
5371
  var isOutput = normalized.startsWith('OUTPUT');
@@ -6255,12 +5373,10 @@
6255
5373
  isInput = false;
6256
5374
  isOutput = false;
6257
5375
  }
6258
- var parameterName = validateParameterName(parameterNameRaw);
6259
- var parameterDescription = parameterDescriptionRaw.trim() || null;
6260
5376
  return {
6261
5377
  type: 'PARAMETER',
6262
5378
  parameterName: parameterName,
6263
- parameterDescription: parameterDescription,
5379
+ parameterDescription: parameterDescription.trim() || null,
6264
5380
  isInput: isInput,
6265
5381
  isOutput: isOutput,
6266
5382
  };
@@ -7010,6 +6126,76 @@
7010
6126
  return str;
7011
6127
  }
7012
6128
 
6129
+ /**
6130
+ * @@@
6131
+ *
6132
+ * @param text @@@
6133
+ * @returns @@@
6134
+ * @example 'HELLO_WORLD'
6135
+ * @example 'I_LOVE_PROMPTBOOK'
6136
+ * @public exported from `@promptbook/utils`
6137
+ */
6138
+ function normalizeTo_SCREAMING_CASE(text) {
6139
+ var e_1, _a;
6140
+ var charType;
6141
+ var lastCharType = 'OTHER';
6142
+ var normalizedName = '';
6143
+ try {
6144
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
6145
+ var char = text_1_1.value;
6146
+ var normalizedChar = void 0;
6147
+ if (/^[a-z]$/.test(char)) {
6148
+ charType = 'LOWERCASE';
6149
+ normalizedChar = char.toUpperCase();
6150
+ }
6151
+ else if (/^[A-Z]$/.test(char)) {
6152
+ charType = 'UPPERCASE';
6153
+ normalizedChar = char;
6154
+ }
6155
+ else if (/^[0-9]$/.test(char)) {
6156
+ charType = 'NUMBER';
6157
+ normalizedChar = char;
6158
+ }
6159
+ else if (/^\/$/.test(char)) {
6160
+ charType = 'SLASH';
6161
+ normalizedChar = char;
6162
+ }
6163
+ else {
6164
+ charType = 'OTHER';
6165
+ normalizedChar = '_';
6166
+ }
6167
+ if (charType !== lastCharType &&
6168
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
6169
+ !(lastCharType === 'NUMBER') &&
6170
+ !(charType === 'NUMBER')) {
6171
+ normalizedName += '_';
6172
+ }
6173
+ normalizedName += normalizedChar;
6174
+ lastCharType = charType;
6175
+ }
6176
+ }
6177
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6178
+ finally {
6179
+ try {
6180
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
6181
+ }
6182
+ finally { if (e_1) throw e_1.error; }
6183
+ }
6184
+ normalizedName = normalizedName.replace(/_+/g, '_');
6185
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
6186
+ normalizedName = normalizedName.replace(/^_/, '');
6187
+ normalizedName = normalizedName.replace(/_$/, '');
6188
+ return normalizedName;
6189
+ }
6190
+ /**
6191
+ * TODO: Tests
6192
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
6193
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
6194
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
6195
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
6196
+ * TODO: [🌺] Use some intermediate util splitWords
6197
+ */
6198
+
7013
6199
  /**
7014
6200
  * Parses one line of ul/ol to command
7015
6201
  *
@@ -7022,7 +6208,6 @@
7022
6208
  if (raw.includes('\n') || raw.includes('\r')) {
7023
6209
  throw new ParseError('Command can not contain new line characters' /* <- TODO: [🚞] */);
7024
6210
  }
7025
- // TODO: Unit test all this processing and parsing
7026
6211
  var normalized = raw.trim();
7027
6212
  normalized = normalized.split('`').join('');
7028
6213
  normalized = normalized.split('"').join('');
@@ -7068,9 +6253,7 @@
7068
6253
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
7069
6254
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
7070
6255
  var args = items.slice(commandNameSegmentsCount + 1);
7071
- var rawArgs = raw
7072
- .substring(commandNameRaw.length)
7073
- .trim();
6256
+ var rawArgs = raw.substring(commandNameRaw.length).trim();
7074
6257
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
7075
6258
  if (command !== null) {
7076
6259
  return command;
@@ -7080,10 +6263,8 @@
7080
6263
  // Arg1 Arg2 Arg3 | FOO
7081
6264
  {
7082
6265
  var commandNameRaw = items.slice(-1).join('_');
7083
- var args = items.slice(0, -1); // <- Note: This is probbably not correct
7084
- var rawArgs = raw
7085
- .substring(0, raw.length - commandNameRaw.length)
7086
- .trim();
6266
+ var args = items.slice(0, -1);
6267
+ var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7087
6268
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
7088
6269
  if (command !== null) {
7089
6270
  return command;
@@ -7223,7 +6404,7 @@
7223
6404
  function extractOneBlockFromMarkdown(markdown) {
7224
6405
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
7225
6406
  if (codeBlocks.length !== 1) {
7226
- 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 "); }));
6407
+ 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 "); }));
7227
6408
  }
7228
6409
  return codeBlocks[0];
7229
6410
  }