@promptbook/core 0.71.0-0 → 0.71.0-13

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 (195) hide show
  1. package/README.md +10 -0
  2. package/esm/index.es.js +1964 -1407
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/browser.index.d.ts +3 -1
  5. package/esm/typings/src/_packages/cli.index.d.ts +20 -0
  6. package/esm/typings/src/_packages/core.index.d.ts +36 -14
  7. package/esm/typings/src/_packages/documents.index.d.ts +8 -0
  8. package/esm/typings/src/_packages/legacy-documents.index.d.ts +8 -0
  9. package/esm/typings/src/_packages/markdown-utils.index.d.ts +6 -0
  10. package/esm/typings/src/_packages/node.index.d.ts +14 -6
  11. package/esm/typings/src/_packages/pdf.index.d.ts +8 -0
  12. package/esm/typings/src/_packages/types.index.d.ts +41 -25
  13. package/esm/typings/src/_packages/website-crawler.index.d.ts +8 -0
  14. package/esm/typings/src/cli/cli-commands/about.d.ts +1 -1
  15. package/esm/typings/src/cli/cli-commands/hello.d.ts +2 -1
  16. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  17. package/esm/typings/src/cli/cli-commands/prettify.d.ts +2 -1
  18. package/esm/typings/src/cli/cli-commands/test-command.d.ts +13 -0
  19. package/esm/typings/src/cli/main.d.ts +1 -1
  20. package/esm/typings/src/cli/promptbookCli.d.ts +1 -1
  21. package/esm/typings/src/collection/constructors/createCollectionFromDirectory.d.ts +11 -6
  22. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  23. package/esm/typings/src/commands/EXPECT/expectCommandParser.d.ts +1 -1
  24. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +5 -1
  25. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -1
  26. package/esm/typings/src/commands/FORMAT/formatCommandParser.d.ts +1 -1
  27. package/esm/typings/src/commands/JOKER/jokerCommandParser.d.ts +1 -1
  28. package/esm/typings/src/commands/KNOWLEDGE/knowledgeCommandParser.d.ts +1 -1
  29. package/esm/typings/src/commands/KNOWLEDGE/utils/sourceContentToName.d.ts +11 -0
  30. package/esm/typings/src/commands/KNOWLEDGE/utils/sourceContentToName.test.d.ts +4 -0
  31. package/esm/typings/src/commands/MODEL/modelCommandParser.d.ts +1 -1
  32. package/esm/typings/src/commands/PARAMETER/parameterCommandParser.d.ts +1 -1
  33. package/esm/typings/src/commands/PERSONA/personaCommandParser.d.ts +1 -1
  34. package/esm/typings/src/commands/POSTPROCESS/postprocessCommandParser.d.ts +1 -1
  35. package/esm/typings/src/commands/PROMPTBOOK_VERSION/promptbookVersionCommandParser.d.ts +1 -1
  36. package/esm/typings/src/commands/TEMPLATE/templateCommandParser.d.ts +1 -1
  37. package/esm/typings/src/commands/URL/urlCommandParser.d.ts +1 -1
  38. package/esm/typings/src/commands/X_ACTION/actionCommandParser.d.ts +1 -1
  39. package/esm/typings/src/commands/X_INSTRUMENT/instrumentCommandParser.d.ts +1 -1
  40. package/esm/typings/src/commands/_BOILERPLATE/boilerplateCommandParser.d.ts +1 -1
  41. package/esm/typings/src/config.d.ts +16 -0
  42. package/esm/typings/src/conversion/pipelineStringToJson.d.ts +4 -15
  43. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  44. package/esm/typings/src/conversion/validation/_importPipeline.d.ts +1 -1
  45. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +5 -5
  46. package/esm/typings/src/{knowledge/dialogs → dialogs}/callback/CallbackInterfaceTools.d.ts +2 -2
  47. package/esm/typings/src/{knowledge/dialogs → dialogs}/callback/CallbackInterfaceToolsOptions.d.ts +3 -3
  48. package/esm/typings/src/{knowledge/dialogs → dialogs}/simple-prompt/SimplePromptInterfaceTools.d.ts +5 -5
  49. package/esm/typings/src/errors/AbstractFormatError.d.ts +11 -0
  50. package/esm/typings/src/errors/KnowledgeScrapeError.d.ts +9 -0
  51. package/esm/typings/src/errors/MissingToolsError.d.ts +9 -0
  52. package/esm/typings/src/execution/{CommonExecutionToolsOptions.d.ts → CommonToolsOptions.d.ts} +1 -1
  53. package/esm/typings/src/execution/ExecutionTools.d.ts +20 -8
  54. package/esm/typings/src/execution/PipelineExecutor.d.ts +1 -0
  55. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +5 -2
  56. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +2 -13
  57. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +3 -0
  58. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +5 -2
  59. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +4 -6
  60. package/esm/typings/src/execution/createPipelineExecutor/{30-executeFormatCells.d.ts → 30-executeFormatSubvalues.d.ts} +2 -6
  61. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +1 -6
  62. package/esm/typings/src/execution/embeddingVectorToString.d.ts +1 -1
  63. package/esm/typings/src/execution/translation/automatic-translate/translateMessages.d.ts +3 -0
  64. package/esm/typings/src/execution/utils/$provideExecutionToolsForNode.d.ts +13 -0
  65. package/esm/typings/src/execution/utils/forEachAsync.d.ts +1 -0
  66. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +2 -1
  67. package/esm/typings/src/formats/csv/CsvFormatError.d.ts +10 -0
  68. package/esm/typings/src/llm-providers/_common/{$llmToolsMetadataRegister.d.ts → register/$llmToolsMetadataRegister.d.ts} +4 -1
  69. package/esm/typings/src/llm-providers/_common/{$llmToolsRegister.d.ts → register/$llmToolsRegister.d.ts} +5 -2
  70. package/esm/typings/src/llm-providers/_common/{createLlmToolsFromConfigurationFromEnv.d.ts → register/$provideLlmToolsConfigurationFromEnv.d.ts} +3 -3
  71. package/esm/typings/src/llm-providers/_common/{getLlmToolsForCli.d.ts → register/$provideLlmToolsForCli.d.ts} +4 -3
  72. package/esm/typings/src/llm-providers/_common/{getLlmToolsForTestingAndScriptsAndPlayground.d.ts → register/$provideLlmToolsForTestingAndScriptsAndPlayground.d.ts} +4 -3
  73. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsFromEnv.d.ts +27 -0
  74. package/esm/typings/src/llm-providers/_common/{$registeredLlmToolsMessage.d.ts → register/$registeredLlmToolsMessage.d.ts} +5 -2
  75. package/esm/typings/src/llm-providers/_common/{LlmToolsConfiguration.d.ts → register/LlmToolsConfiguration.d.ts} +5 -4
  76. package/esm/typings/src/llm-providers/_common/{LlmToolsMetadata.d.ts → register/LlmToolsMetadata.d.ts} +5 -4
  77. package/esm/typings/src/llm-providers/_common/{LlmToolsOptions.d.ts → register/LlmToolsOptions.d.ts} +4 -1
  78. package/esm/typings/src/llm-providers/_common/{createLlmToolsFromConfiguration.d.ts → register/createLlmToolsFromConfiguration.d.ts} +5 -4
  79. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +2 -1
  80. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +3 -3
  81. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +3 -2
  82. package/esm/typings/src/llm-providers/anthropic-claude/register-configuration.d.ts +4 -3
  83. package/esm/typings/src/llm-providers/anthropic-claude/register-constructor.d.ts +4 -3
  84. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +8 -1
  85. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +2 -2
  86. package/esm/typings/src/llm-providers/azure-openai/playground/playground.d.ts +1 -0
  87. package/esm/typings/src/llm-providers/azure-openai/register-configuration.d.ts +4 -3
  88. package/esm/typings/src/llm-providers/azure-openai/register-constructor.d.ts +4 -3
  89. package/esm/typings/src/llm-providers/langtail/playground/playground.d.ts +3 -0
  90. package/esm/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +2 -2
  91. package/esm/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +2 -2
  92. package/esm/typings/src/llm-providers/multiple/MultipleLlmExecutionTools.d.ts +1 -0
  93. package/esm/typings/src/llm-providers/multiple/playground/playground.d.ts +3 -0
  94. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +2 -1
  95. package/esm/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +2 -2
  96. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +2 -1
  97. package/esm/typings/src/llm-providers/openai/register-configuration.d.ts +4 -3
  98. package/esm/typings/src/llm-providers/openai/register-constructor.d.ts +4 -3
  99. package/esm/typings/src/llm-providers/remote/interfaces/PromptbookServer_ListModels_Request.d.ts +1 -1
  100. package/esm/typings/src/llm-providers/remote/interfaces/PromptbookServer_Prompt_Request.d.ts +1 -1
  101. package/esm/typings/src/llm-providers/remote/interfaces/RemoteLlmExecutionToolsOptions.d.ts +3 -3
  102. package/esm/typings/src/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +2 -2
  103. package/esm/typings/src/llm-providers/remote/playground/playground.d.ts +3 -0
  104. package/esm/typings/src/personas/preparePersona.d.ts +3 -2
  105. package/esm/typings/src/prepare/PrepareAndScrapeOptions.d.ts +68 -0
  106. package/esm/typings/src/prepare/preparePipeline.d.ts +3 -2
  107. package/esm/typings/src/prepare/prepareTemplates.d.ts +3 -2
  108. package/esm/typings/src/scrapers/_common/Converter.d.ts +22 -0
  109. package/esm/typings/src/scrapers/_common/Scraper.d.ts +66 -0
  110. package/esm/typings/src/scrapers/_common/ScraperIntermediateSource.d.ts +11 -0
  111. package/esm/typings/src/{knowledge/prepare-knowledge → scrapers}/_common/prepareKnowledgePieces.d.ts +5 -4
  112. package/esm/typings/src/scrapers/_common/register/$provideScrapersForBrowser.d.ts +12 -0
  113. package/esm/typings/src/scrapers/_common/register/$provideScrapersForNode.d.ts +15 -0
  114. package/esm/typings/src/scrapers/_common/register/$registeredScrapersMessage.d.ts +12 -0
  115. package/esm/typings/src/scrapers/_common/register/$scrapersMetadataRegister.d.ts +13 -0
  116. package/esm/typings/src/scrapers/_common/register/$scrapersRegister.d.ts +13 -0
  117. package/esm/typings/src/scrapers/_common/register/ScraperAndConverterMetadata.d.ts +41 -0
  118. package/esm/typings/src/scrapers/_common/register/ScraperConstructor.d.ts +12 -0
  119. package/esm/typings/src/scrapers/_common/utils/getScraperIntermediateSource.d.ts +33 -0
  120. package/esm/typings/src/scrapers/_common/utils/getScraperIntermediateSource.test.d.ts +4 -0
  121. package/esm/typings/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +13 -0
  122. package/esm/typings/src/scrapers/document/DocumentScraper.d.ts +43 -0
  123. package/esm/typings/src/scrapers/document/DocumentScraper.test.d.ts +4 -0
  124. package/esm/typings/src/scrapers/document/createDocumentScraper.d.ts +20 -0
  125. package/esm/typings/src/scrapers/document/playground/document-scraper-playground.d.ts +5 -0
  126. package/esm/typings/src/scrapers/document/register-constructor.d.ts +13 -0
  127. package/esm/typings/src/scrapers/document/register-metadata.d.ts +24 -0
  128. package/esm/typings/src/scrapers/document-legacy/LegacyDocumentScraper.d.ts +43 -0
  129. package/esm/typings/src/scrapers/document-legacy/LegacyDocumentScraper.test.d.ts +4 -0
  130. package/esm/typings/src/scrapers/document-legacy/createLegacyDocumentScraper.d.ts +20 -0
  131. package/esm/typings/src/scrapers/document-legacy/playground/legacy-document-scraper-playground.d.ts +5 -0
  132. package/esm/typings/src/scrapers/document-legacy/register-constructor.d.ts +13 -0
  133. package/esm/typings/src/scrapers/document-legacy/register-metadata.d.ts +24 -0
  134. package/esm/typings/src/scrapers/markdown/MarkdownScraper.d.ts +29 -0
  135. package/esm/typings/src/scrapers/markdown/createMarkdownScraper.d.ts +20 -0
  136. package/esm/typings/src/scrapers/markdown/playground/markdown-scraper-playground.d.ts +5 -0
  137. package/esm/typings/src/scrapers/markdown/register-constructor.d.ts +13 -0
  138. package/esm/typings/src/scrapers/markdown/register-metadata.d.ts +24 -0
  139. package/esm/typings/src/scrapers/pdf/PdfScraper.d.ts +40 -0
  140. package/esm/typings/src/scrapers/pdf/createPdfScraper.d.ts +20 -0
  141. package/esm/typings/src/scrapers/pdf/playground/pdf-scraper-playground.d.ts +5 -0
  142. package/esm/typings/src/scrapers/pdf/register-constructor.d.ts +13 -0
  143. package/esm/typings/src/scrapers/pdf/register-metadata.d.ts +24 -0
  144. package/esm/typings/src/scrapers/website/WebsiteScraper.d.ts +47 -0
  145. package/esm/typings/src/scrapers/website/createWebsiteScraper.d.ts +20 -0
  146. package/esm/typings/src/scrapers/website/playground/website-scraper-playground.d.ts +5 -0
  147. package/esm/typings/src/scrapers/website/register-constructor.d.ts +13 -0
  148. package/esm/typings/src/scrapers/website/register-metadata.d.ts +24 -0
  149. package/esm/typings/src/scrapers/website/utils/markdownConverter.d.ts +12 -0
  150. package/esm/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +2 -2
  151. package/esm/typings/src/scripting/python/PythonExecutionTools.d.ts +2 -2
  152. package/esm/typings/src/scripting/typescript/TypescriptExecutionTools.d.ts +2 -2
  153. package/esm/typings/src/storage/{files-storage/FilesStorage.d.ts → file-cache-storage/FileCacheStorage.d.ts} +4 -4
  154. package/esm/typings/src/storage/file-cache-storage/FileCacheStorageOptions.d.ts +10 -0
  155. package/esm/typings/src/storage/{files-storage → file-cache-storage}/utils/nameToSubfolderPath.d.ts +1 -1
  156. package/esm/typings/src/storage/file-cache-storage/utils/nameToSubfolderPath.test.d.ts +1 -0
  157. package/esm/typings/src/storage/local-storage/getLocalStorage.d.ts +1 -1
  158. package/esm/typings/src/storage/local-storage/getSessionStorage.d.ts +1 -1
  159. package/esm/typings/src/storage/{utils → memory/utils}/PrefixStorage.d.ts +1 -1
  160. package/esm/typings/src/storage/{utils → memory/utils}/makePromptbookStorageFromWebStorage.d.ts +1 -1
  161. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -1
  162. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +2 -2
  163. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +0 -3
  164. package/esm/typings/src/types/execution-report/executionReportJsonToString.d.ts +2 -1
  165. package/esm/typings/src/types/typeAliases.d.ts +16 -12
  166. package/esm/typings/src/utils/$Register.d.ts +19 -6
  167. package/esm/typings/src/utils/execCommand/$execCommand.d.ts +14 -0
  168. package/esm/typings/src/utils/execCommand/$execCommands.d.ts +17 -0
  169. package/esm/typings/src/utils/execCommand/IExecCommandOptions.d.ts +23 -0
  170. package/esm/typings/src/utils/execCommand/execCommand.test.d.ts +1 -0
  171. package/esm/typings/src/utils/execCommand/execCommandNormalizeOptions.d.ts +10 -0
  172. package/esm/typings/src/utils/execCommand/execCommandNormalizeOptions.test.d.ts +1 -0
  173. package/esm/typings/src/utils/files/$isDirectoryExisting.d.ts +3 -3
  174. package/esm/typings/src/utils/files/$isFileExisting.d.ts +3 -3
  175. package/esm/typings/src/utils/files/$listAllFiles.d.ts +5 -4
  176. package/esm/typings/src/utils/files/extensionToMimeType.d.ts +8 -0
  177. package/esm/typings/src/utils/files/extensionToMimeType.test.d.ts +1 -0
  178. package/esm/typings/src/utils/files/getFileExtension.d.ts +8 -0
  179. package/esm/typings/src/utils/files/getFileExtension.test.d.ts +1 -0
  180. package/esm/typings/src/utils/validators/filePath/isValidFilePath.d.ts +2 -2
  181. package/package.json +2 -1
  182. package/umd/index.umd.js +1976 -1411
  183. package/umd/index.umd.js.map +1 -1
  184. package/esm/typings/src/knowledge/prepare-knowledge/_common/Scraper.d.ts +0 -37
  185. package/esm/typings/src/knowledge/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -2
  186. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -14
  187. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +0 -15
  188. package/esm/typings/src/llm-providers/_common/createLlmToolsFromEnv.d.ts +0 -25
  189. package/esm/typings/src/prepare/PrepareOptions.d.ts +0 -22
  190. package/esm/typings/src/storage/files-storage/FilesStorageOptions.d.ts +0 -10
  191. /package/esm/typings/src/{knowledge/dialogs → dialogs}/user-interface-execution-tools.test.d.ts +0 -0
  192. /package/esm/typings/src/{knowledge/prepare-knowledge → scrapers}/_common/prepareKnowledgePieces.test.d.ts +0 -0
  193. /package/esm/typings/src/{knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts → scrapers/markdown/MarkdownScraper.test.d.ts} +0 -0
  194. /package/esm/typings/src/{knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts → scrapers/website/WebsiteScraper.test.d.ts} +0 -0
  195. /package/esm/typings/src/{storage/files-storage/utils/nameToSubfolderPath.test.d.ts → scrapers/website/utils/markdownConverter.test.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -3,7 +3,11 @@ import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
4
  import { forTime } from 'waitasecond';
5
5
  import { unparse, parse } from 'papaparse';
6
+ import { stat, access, constants, readFile } from 'fs/promises';
7
+ import { join, basename } from 'path';
8
+ import { SHA256 } from 'crypto-js';
6
9
  import hexEncoder from 'crypto-js/enc-hex';
10
+ import { lookup } from 'mime-types';
7
11
  import sha256 from 'crypto-js/sha256';
8
12
  import moment from 'moment';
9
13
 
@@ -11,8 +15,8 @@ import moment from 'moment';
11
15
  /**
12
16
  * The version of the Promptbook library
13
17
  */
14
- var PROMPTBOOK_VERSION = '0.70.0-1';
15
- // TODO:[main] !!!! List here all the versions and annotate + put into script
18
+ var PROMPTBOOK_VERSION = '0.71.0-12';
19
+ // TODO: [main] !!!! List here all the versions and annotate + put into script
16
20
 
17
21
  /*! *****************************************************************************
18
22
  Copyright (c) Microsoft Corporation.
@@ -224,7 +228,7 @@ function pipelineJsonToString(pipelineJson) {
224
228
  commands.push("PIPELINE URL ".concat(pipelineUrl));
225
229
  }
226
230
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
227
- // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
231
+ // TODO: [main] !!! This increase size of the bundle and is probbably not necessary
228
232
  pipelineString = prettifyMarkdown(pipelineString);
229
233
  try {
230
234
  for (var _g = __values(parameters.filter(function (_a) {
@@ -372,12 +376,12 @@ function pipelineJsonToString(pipelineJson) {
372
376
  pipelineString += '```' + contentLanguage;
373
377
  pipelineString += '\n';
374
378
  pipelineString += spaceTrim(content);
375
- // <- TODO:[main] !!! Escape
379
+ // <- TODO: [main] !!! Escape
376
380
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
377
381
  pipelineString += '\n';
378
382
  pipelineString += '```';
379
383
  pipelineString += '\n\n';
380
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
384
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: [main] !!! If the parameter here has description, add it and use templateParameterJsonToString
381
385
  }
382
386
  }
383
387
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -683,9 +687,19 @@ var MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL = 200;
683
687
  /**
684
688
  * Where to store the cache of executions for promptbook CLI
685
689
  *
690
+ * Note: When the folder does not exist, it is created recursively
691
+ *
686
692
  * @public exported from `@promptbook/core`
687
693
  */
688
694
  var EXECUTIONS_CACHE_DIRNAME = '/.promptbook/executions-cache';
695
+ /**
696
+ * Where to store the scrape cache
697
+ *
698
+ * Note: When the folder does not exist, it is created recursively
699
+ *
700
+ * @public exported from `@promptbook/core`
701
+ */
702
+ var SCRAPE_CACHE_DIRNAME = '/.promptbook/scrape-cache';
689
703
  /**
690
704
  * The name of the builded pipeline collection made by CLI `ptbk make` and for lookup in `createCollectionFromDirectory`
691
705
  *
@@ -765,6 +779,12 @@ var DEFAULT_CSV_SETTINGS = Object.freeze({
765
779
  * @public exported from `@promptbook/core`
766
780
  */
767
781
  var IS_VERBOSE = false;
782
+ /**
783
+ * @@@
784
+ *
785
+ * @public exported from `@promptbook/core`
786
+ */
787
+ var IS_AUTO_INSTALLED = false;
768
788
  /**
769
789
  * @@@
770
790
  *
@@ -851,7 +871,7 @@ function isValidPromptbookVersion(version) {
851
871
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
852
872
  return false;
853
873
  }
854
- // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
874
+ // <- TODO: [main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
855
875
  return true;
856
876
  }
857
877
 
@@ -1215,11 +1235,11 @@ function validatePipelineCore(pipeline) {
1215
1235
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1216
1236
  */
1217
1237
  /**
1218
- * TODO: [🐣][main] !!!! Validate that all samples match expectations
1219
- * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1220
- * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1221
- * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1222
- * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1238
+ * TODO: [🧳][main] !!!! Validate that all samples match expectations
1239
+ * TODO: [🧳][🐝][main] !!!! Validate that knowledge is valid (non-void)
1240
+ * TODO: [🧳][main] !!!! Validate that persona can be used only with CHAT variant
1241
+ * TODO: [🧳][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1242
+ * TODO: [🧳][main] !!!! Validate that reserved parameter is not used as joker
1223
1243
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1224
1244
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1225
1245
  */
@@ -1533,7 +1553,7 @@ function createCollectionFromUrl(url, options) {
1533
1553
  });
1534
1554
  }
1535
1555
  /**
1536
- * TODO:[main] !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1556
+ * TODO: [main] !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1537
1557
  */
1538
1558
 
1539
1559
  /**
@@ -1634,6 +1654,22 @@ var TemplateTypes = [
1634
1654
  // <- [🅱]
1635
1655
  ];
1636
1656
 
1657
+ /**
1658
+ * This error type indicates that some tools are missing for pipeline execution or preparation
1659
+ *
1660
+ * @public exported from `@promptbook/core`
1661
+ */
1662
+ var MissingToolsError = /** @class */ (function (_super) {
1663
+ __extends(MissingToolsError, _super);
1664
+ function MissingToolsError(message) {
1665
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: You have probbably forgot to provide some tools for pipeline execution or preparation\n\n "); })) || this;
1666
+ _this.name = 'MissingToolsError';
1667
+ Object.setPrototypeOf(_this, MissingToolsError.prototype);
1668
+ return _this;
1669
+ }
1670
+ return MissingToolsError;
1671
+ }(Error));
1672
+
1637
1673
  /**
1638
1674
  * @@@
1639
1675
  *
@@ -1762,6 +1798,7 @@ function addUsage() {
1762
1798
  * @param options - Options for the function
1763
1799
  * @param callbackfunction - Function to call for each item
1764
1800
  * @public exported from `@promptbook/utils`
1801
+ * @deprecated [🪂] Use queues instead
1765
1802
  */
1766
1803
  function forEachAsync(array, options, callbackfunction) {
1767
1804
  return __awaiter(this, void 0, void 0, function () {
@@ -1830,370 +1867,92 @@ function forEachAsync(array, options, callbackfunction) {
1830
1867
  });
1831
1868
  }
1832
1869
 
1833
- 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"}];
1834
-
1835
- var defaultDiacriticsRemovalMap = [
1836
- {
1837
- base: 'A',
1838
- letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
1839
- },
1840
- { base: 'AA', letters: '\uA732' },
1841
- { base: 'AE', letters: '\u00C6\u01FC\u01E2' },
1842
- { base: 'AO', letters: '\uA734' },
1843
- { base: 'AU', letters: '\uA736' },
1844
- { base: 'AV', letters: '\uA738\uA73A' },
1845
- { base: 'AY', letters: '\uA73C' },
1846
- {
1847
- base: 'B',
1848
- letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
1849
- },
1850
- {
1851
- base: 'C',
1852
- letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
1853
- },
1854
- {
1855
- base: 'D',
1856
- letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
1857
- },
1858
- { base: 'DZ', letters: '\u01F1\u01C4' },
1859
- { base: 'Dz', letters: '\u01F2\u01C5' },
1860
- {
1861
- base: 'E',
1862
- letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E',
1863
- },
1864
- { base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
1865
- {
1866
- base: 'G',
1867
- letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
1868
- },
1869
- {
1870
- base: 'H',
1871
- letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
1872
- },
1873
- {
1874
- base: 'I',
1875
- letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
1876
- },
1877
- { base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
1878
- {
1879
- base: 'K',
1880
- letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
1881
- },
1882
- {
1883
- base: 'L',
1884
- letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
1885
- },
1886
- { base: 'LJ', letters: '\u01C7' },
1887
- { base: 'Lj', letters: '\u01C8' },
1888
- { base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
1889
- {
1890
- base: 'N',
1891
- letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
1892
- },
1893
- { base: 'NJ', letters: '\u01CA' },
1894
- { base: 'Nj', letters: '\u01CB' },
1895
- {
1896
- base: 'O',
1897
- letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C',
1898
- },
1899
- { base: 'OI', letters: '\u01A2' },
1900
- { base: 'OO', letters: '\uA74E' },
1901
- { base: 'OU', letters: '\u0222' },
1902
- { base: 'OE', letters: '\u008C\u0152' },
1903
- { base: 'oe', letters: '\u009C\u0153' },
1904
- {
1905
- base: 'P',
1906
- letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
1907
- },
1908
- { base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
1909
- {
1910
- base: 'R',
1911
- letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
1912
- },
1913
- {
1914
- base: 'S',
1915
- letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
1916
- },
1917
- {
1918
- base: 'T',
1919
- letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
1920
- },
1921
- { base: 'TZ', letters: '\uA728' },
1922
- {
1923
- base: 'U',
1924
- letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
1925
- },
1926
- { base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
1927
- { base: 'VY', letters: '\uA760' },
1928
- {
1929
- base: 'W',
1930
- letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
1931
- },
1932
- { base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
1933
- {
1934
- base: 'Y',
1935
- letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
1936
- },
1937
- {
1938
- base: 'Z',
1939
- letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
1940
- },
1941
- {
1942
- base: 'a',
1943
- letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250',
1944
- },
1945
- { base: 'aa', letters: '\uA733' },
1946
- { base: 'ae', letters: '\u00E6\u01FD\u01E3' },
1947
- { base: 'ao', letters: '\uA735' },
1948
- { base: 'au', letters: '\uA737' },
1949
- { base: 'av', letters: '\uA739\uA73B' },
1950
- { base: 'ay', letters: '\uA73D' },
1951
- {
1952
- base: 'b',
1953
- letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
1954
- },
1955
- {
1956
- base: 'c',
1957
- letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184',
1958
- },
1959
- {
1960
- base: 'd',
1961
- letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
1962
- },
1963
- { base: 'dz', letters: '\u01F3\u01C6' },
1964
- {
1965
- base: 'e',
1966
- letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
1967
- },
1968
- { base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
1969
- {
1970
- base: 'g',
1971
- letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
1972
- },
1973
- {
1974
- base: 'h',
1975
- letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
1976
- },
1977
- { base: 'hv', letters: '\u0195' },
1978
- {
1979
- base: 'i',
1980
- letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131',
1981
- },
1982
- { base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
1983
- {
1984
- base: 'k',
1985
- letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
1986
- },
1987
- {
1988
- base: 'l',
1989
- letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
1990
- },
1991
- { base: 'lj', letters: '\u01C9' },
1992
- { base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
1993
- {
1994
- base: 'n',
1995
- letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
1996
- },
1997
- { base: 'nj', letters: '\u01CC' },
1998
- {
1999
- base: 'o',
2000
- letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275',
2001
- },
2002
- { base: 'oi', letters: '\u01A3' },
2003
- { base: 'ou', letters: '\u0223' },
2004
- { base: 'oo', letters: '\uA74F' },
2005
- {
2006
- base: 'p',
2007
- letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
2008
- },
2009
- { base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
2010
- {
2011
- base: 'r',
2012
- letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
2013
- },
2014
- {
2015
- base: 's',
2016
- letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
2017
- },
2018
- {
2019
- base: 't',
2020
- letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
2021
- },
2022
- { base: 'tz', letters: '\uA729' },
2023
- {
2024
- base: 'u',
2025
- letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289',
2026
- },
2027
- { base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
2028
- { base: 'vy', letters: '\uA761' },
2029
- {
2030
- base: 'w',
2031
- letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
2032
- },
2033
- { base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
2034
- {
2035
- base: 'y',
2036
- letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
2037
- },
2038
- {
2039
- base: 'z',
2040
- letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
2041
- },
2042
- ];
2043
1870
  /**
2044
- * Map of letters from diacritic variant to diacritless variant
2045
- * Contains lowercase and uppercase separatelly
2046
- *
2047
- * > "á" => "a"
2048
- * > "ě" => "e"
2049
- * > "Ă" => "A"
2050
- * > ...
1871
+ * Intercepts LLM tools and counts total usage of the tools
2051
1872
  *
2052
- * @public exported from `@promptbook/utils`
1873
+ * @param llmTools LLM tools to be intercepted with usage counting
1874
+ * @returns LLM tools with same functionality with added total cost counting
1875
+ * @public exported from `@promptbook/core`
2053
1876
  */
2054
- var DIACRITIC_VARIANTS_LETTERS = {};
2055
- // tslint:disable-next-line: prefer-for-of
2056
- for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
2057
- var letters = defaultDiacriticsRemovalMap[i].letters;
2058
- // tslint:disable-next-line: prefer-for-of
2059
- for (var j = 0; j < letters.length; j++) {
2060
- DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
2061
- }
2062
- }
2063
- // <- TODO: [🍓] Put to maker function to save execution time if not needed
2064
- /*
2065
- @see https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
2066
- Licensed under the Apache License, Version 2.0 (the "License");
2067
- you may not use this file except in compliance with the License.
2068
- You may obtain a copy of the License at
2069
-
2070
- http://www.apache.org/licenses/LICENSE-2.0
2071
-
2072
- Unless required by applicable law or agreed to in writing, software
2073
- distributed under the License is distributed on an "AS IS" BASIS,
2074
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2075
- See the License for the specific language governing permissions and
2076
- limitations under the License.
2077
- */
2078
-
2079
- /**
2080
- * @@@
2081
- *
2082
- * @param input @@@
2083
- * @returns @@@
2084
- * @public exported from `@promptbook/utils`
2085
- */
2086
- function removeDiacritics(input) {
2087
- /*eslint no-control-regex: "off"*/
2088
- return input.replace(/[^\u0000-\u007E]/g, function (a) {
2089
- return DIACRITIC_VARIANTS_LETTERS[a] || a;
2090
- });
2091
- }
2092
- /**
2093
- * TODO: [Ж] Variant for cyrillic (and in general non-latin) letters
2094
- */
2095
-
2096
- /**
2097
- * @@@
2098
- *
2099
- * @param text @@@
2100
- * @returns @@@
2101
- * @example 'hello-world'
2102
- * @example 'i-love-promptbook'
2103
- * @public exported from `@promptbook/utils`
2104
- */
2105
- function normalizeToKebabCase(text) {
2106
- var e_1, _a;
2107
- text = removeDiacritics(text);
2108
- var charType;
2109
- var lastCharType = 'OTHER';
2110
- var normalizedName = '';
2111
- try {
2112
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
2113
- var char = text_1_1.value;
2114
- var normalizedChar = void 0;
2115
- if (/^[a-z]$/.test(char)) {
2116
- charType = 'LOWERCASE';
2117
- normalizedChar = char;
2118
- }
2119
- else if (/^[A-Z]$/.test(char)) {
2120
- charType = 'UPPERCASE';
2121
- normalizedChar = char.toLowerCase();
2122
- }
2123
- else if (/^[0-9]$/.test(char)) {
2124
- charType = 'NUMBER';
2125
- normalizedChar = char;
2126
- }
2127
- else if (/^\/$/.test(char)) {
2128
- charType = 'SLASH';
2129
- normalizedChar = char;
2130
- }
2131
- else {
2132
- charType = 'OTHER';
2133
- normalizedChar = '-';
2134
- }
2135
- if (charType !== lastCharType &&
2136
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
2137
- !(lastCharType === 'NUMBER') &&
2138
- !(charType === 'NUMBER')) {
2139
- normalizedName += '-';
2140
- }
2141
- normalizedName += normalizedChar;
2142
- lastCharType = charType;
2143
- }
1877
+ function countTotalUsage(llmTools) {
1878
+ var _this = this;
1879
+ var totalUsage = ZERO_USAGE;
1880
+ var proxyTools = {
1881
+ get title() {
1882
+ // TODO: [🧠] Maybe put here some suffix
1883
+ return llmTools.title;
1884
+ },
1885
+ get description() {
1886
+ // TODO: [🧠] Maybe put here some suffix
1887
+ return llmTools.description;
1888
+ },
1889
+ checkConfiguration: function () {
1890
+ return __awaiter(this, void 0, void 0, function () {
1891
+ return __generator(this, function (_a) {
1892
+ return [2 /*return*/, /* not await */ llmTools.checkConfiguration()];
1893
+ });
1894
+ });
1895
+ },
1896
+ listModels: function () {
1897
+ return /* not await */ llmTools.listModels();
1898
+ },
1899
+ getTotalUsage: function () {
1900
+ // <- Note: [🥫] Not using getter `get totalUsage` but `getTotalUsage` to allow this object to be proxied
1901
+ return totalUsage;
1902
+ },
1903
+ };
1904
+ if (llmTools.callChatModel !== undefined) {
1905
+ proxyTools.callChatModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
1906
+ var promptResult;
1907
+ return __generator(this, function (_a) {
1908
+ switch (_a.label) {
1909
+ case 0: return [4 /*yield*/, llmTools.callChatModel(prompt)];
1910
+ case 1:
1911
+ promptResult = _a.sent();
1912
+ totalUsage = addUsage(totalUsage, promptResult.usage);
1913
+ return [2 /*return*/, promptResult];
1914
+ }
1915
+ });
1916
+ }); };
2144
1917
  }
2145
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2146
- finally {
2147
- try {
2148
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
2149
- }
2150
- finally { if (e_1) throw e_1.error; }
1918
+ if (llmTools.callCompletionModel !== undefined) {
1919
+ proxyTools.callCompletionModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
1920
+ var promptResult;
1921
+ return __generator(this, function (_a) {
1922
+ switch (_a.label) {
1923
+ case 0: return [4 /*yield*/, llmTools.callCompletionModel(prompt)];
1924
+ case 1:
1925
+ promptResult = _a.sent();
1926
+ totalUsage = addUsage(totalUsage, promptResult.usage);
1927
+ return [2 /*return*/, promptResult];
1928
+ }
1929
+ });
1930
+ }); };
2151
1931
  }
2152
- normalizedName = normalizedName.split(/-+/g).join('-');
2153
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
2154
- normalizedName = normalizedName.replace(/^-/, '');
2155
- normalizedName = normalizedName.replace(/-$/, '');
2156
- return normalizedName;
2157
- }
2158
-
2159
- /**
2160
- * Removes emojis from a string and fix whitespaces
2161
- *
2162
- * @param text with emojis
2163
- * @returns text without emojis
2164
- * @public exported from `@promptbook/utils`
2165
- */
2166
- function removeEmojis(text) {
2167
- // Replace emojis (and also ZWJ sequence) with hyphens
2168
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2169
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2170
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
2171
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
2172
- return text;
1932
+ if (llmTools.callEmbeddingModel !== undefined) {
1933
+ proxyTools.callEmbeddingModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
1934
+ var promptResult;
1935
+ return __generator(this, function (_a) {
1936
+ switch (_a.label) {
1937
+ case 0: return [4 /*yield*/, llmTools.callEmbeddingModel(prompt)];
1938
+ case 1:
1939
+ promptResult = _a.sent();
1940
+ totalUsage = addUsage(totalUsage, promptResult.usage);
1941
+ return [2 /*return*/, promptResult];
1942
+ }
1943
+ });
1944
+ }); };
1945
+ }
1946
+ // <- Note: [🤖]
1947
+ return proxyTools;
2173
1948
  }
2174
-
2175
1949
  /**
2176
- * @@@
2177
- *
2178
- * @param value @@@
2179
- * @returns @@@
2180
- * @example @@@
2181
- * @public exported from `@promptbook/utils`
1950
+ * TODO: [🧠][💸] Maybe make some common abstraction `interceptLlmTools` and use here (or use javascript Proxy?)
1951
+ * TODO: [🧠] Is there some meaningfull way how to test this util
1952
+ * TODO: [🧠][🌯] Maybe a way how to hide ability to `get totalUsage`
1953
+ * > const [llmToolsWithUsage,getUsage] = countTotalUsage(llmTools);
1954
+ * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
2182
1955
  */
2183
- function titleToName(value) {
2184
- if (value.startsWith('http://') || value.startsWith('https://')) {
2185
- // TODO: Maybe check against some list unallowed characters
2186
- return value;
2187
- }
2188
- if (value.startsWith('./') || value.startsWith('../')) {
2189
- // TODO: Maybe check against some list unallowed characters
2190
- return value;
2191
- }
2192
- value = removeEmojis(value);
2193
- value = normalizeToKebabCase(value);
2194
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
2195
- return value;
2196
- }
2197
1956
 
2198
1957
  /**
2199
1958
  * This error indicates errors during the execution of the pipeline
@@ -2212,217 +1971,22 @@ var PipelineExecutionError = /** @class */ (function (_super) {
2212
1971
  }(Error));
2213
1972
 
2214
1973
  /**
2215
- * This error indicates that the pipeline collection cannot be propperly loaded
2216
- *
2217
- * @public exported from `@promptbook/core`
2218
- */
2219
- var CollectionError = /** @class */ (function (_super) {
2220
- __extends(CollectionError, _super);
2221
- function CollectionError(message) {
2222
- var _this = _super.call(this, message) || this;
2223
- _this.name = 'CollectionError';
2224
- Object.setPrototypeOf(_this, CollectionError.prototype);
2225
- return _this;
2226
- }
2227
- return CollectionError;
2228
- }(Error));
2229
-
2230
- /**
2231
- * This error type indicates that you try to use a feature that is not available in the current environment
2232
- *
2233
- * @public exported from `@promptbook/core`
2234
- */
2235
- var EnvironmentMismatchError = /** @class */ (function (_super) {
2236
- __extends(EnvironmentMismatchError, _super);
2237
- function EnvironmentMismatchError(message) {
2238
- var _this = _super.call(this, message) || this;
2239
- _this.name = 'EnvironmentMismatchError';
2240
- Object.setPrototypeOf(_this, EnvironmentMismatchError.prototype);
2241
- return _this;
2242
- }
2243
- return EnvironmentMismatchError;
2244
- }(Error));
2245
-
2246
- /**
2247
- * This error occurs when some expectation is not met in the execution of the pipeline
1974
+ * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2248
1975
  *
2249
- * @public exported from `@promptbook/core`
2250
- * Note: Do not throw this error, its reserved for `checkExpectations` and `createPipelineExecutor` and public ONLY to be serializable through remote server
2251
- * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
2252
- * Note: This is a kindof subtype of PipelineExecutionError
1976
+ * Note: Internal utility of `joinLlmExecutionTools` but exposed type
1977
+ * @public exported from `@promptbook/types`
1978
+ * TODO: !!!!!! Export as runtime class not just type
2253
1979
  */
2254
- var ExpectError = /** @class */ (function (_super) {
2255
- __extends(ExpectError, _super);
2256
- function ExpectError(message) {
2257
- var _this = _super.call(this, message) || this;
2258
- _this.name = 'ExpectError';
2259
- Object.setPrototypeOf(_this, ExpectError.prototype);
2260
- return _this;
2261
- }
2262
- return ExpectError;
2263
- }(Error));
2264
-
2265
- /**
2266
- * This error type indicates that some limit was reached
2267
- *
2268
- * @public exported from `@promptbook/core`
2269
- */
2270
- var LimitReachedError = /** @class */ (function (_super) {
2271
- __extends(LimitReachedError, _super);
2272
- function LimitReachedError(message) {
2273
- var _this = _super.call(this, message) || this;
2274
- _this.name = 'LimitReachedError';
2275
- Object.setPrototypeOf(_this, LimitReachedError.prototype);
2276
- return _this;
2277
- }
2278
- return LimitReachedError;
2279
- }(Error));
2280
-
2281
- /**
2282
- * This error type indicates that some part of the code is not implemented yet
2283
- *
2284
- * @public exported from `@promptbook/core`
2285
- */
2286
- var NotYetImplementedError = /** @class */ (function (_super) {
2287
- __extends(NotYetImplementedError, _super);
2288
- function NotYetImplementedError(message) {
2289
- var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This feature is not implemented yet but it will be soon.\n\n If you want speed up the implementation or just read more, look here:\n https://github.com/webgptorg/promptbook\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
2290
- _this.name = 'NotYetImplementedError';
2291
- Object.setPrototypeOf(_this, NotYetImplementedError.prototype);
2292
- return _this;
2293
- }
2294
- return NotYetImplementedError;
2295
- }(Error));
2296
-
2297
- /**
2298
- * Index of all custom errors
2299
- *
2300
- * @public exported from `@promptbook/core`
2301
- */
2302
- var ERRORS = {
2303
- ExpectError: ExpectError,
2304
- CollectionError: CollectionError,
2305
- EnvironmentMismatchError: EnvironmentMismatchError,
2306
- LimitReachedError: LimitReachedError,
2307
- NotFoundError: NotFoundError,
2308
- NotYetImplementedError: NotYetImplementedError,
2309
- ParseError: ParseError,
2310
- PipelineExecutionError: PipelineExecutionError,
2311
- PipelineLogicError: PipelineLogicError,
2312
- PipelineUrlError: PipelineUrlError,
2313
- UnexpectedError: UnexpectedError,
2314
- // TODO: [🪑]> VersionMismatchError,
2315
- };
2316
-
2317
- /**
2318
- * Deserializes the error object
2319
- *
2320
- * @public exported from `@promptbook/utils`
2321
- */
2322
- function deserializeError(error) {
2323
- if (error.name === 'Error') {
2324
- return new Error(error.message);
2325
- }
2326
- var CustomError = ERRORS[error.name];
2327
- return new CustomError(error.message);
2328
- }
2329
-
2330
- /**
2331
- * Asserts that the execution of a Promptbook is successful
2332
- *
2333
- * @param executionResult - The partial result of the Promptbook execution
2334
- * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2335
- * @public exported from `@promptbook/core`
2336
- */
2337
- function assertsExecutionSuccessful(executionResult) {
2338
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2339
- if (isSuccessful === true) {
2340
- return;
2341
- }
2342
- if (errors.length === 0) {
2343
- throw new PipelineExecutionError("Promptbook Execution failed because of unknown reason");
2344
- }
2345
- else if (errors.length === 1) {
2346
- throw deserializeError(errors[0]);
2347
- }
2348
- else {
2349
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Multiple errors occurred during Promptbook execution\n\n ".concat(block(errors
2350
- .map(function (_a, index) {
2351
- var name = _a.name, stack = _a.stack, message = _a.message;
2352
- return spaceTrim$1(function (block) { return "\n ".concat(name, " ").concat(index + 1, ":\n ").concat(block(stack || message), "\n "); });
2353
- })
2354
- .join('\n')), "\n "); }));
2355
- }
2356
- }
2357
- /**
2358
- * TODO: [🧠] Can this return type be better typed than void
2359
- */
2360
-
2361
- /**
2362
- * Determine if the pipeline is fully prepared
2363
- *
2364
- * @public exported from `@promptbook/core`
2365
- */
2366
- function isPipelinePrepared(pipeline) {
2367
- // Note: Ignoring `pipeline.preparations` @@@
2368
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2369
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2370
- return false;
2371
- }
2372
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2373
- return false;
2374
- }
2375
- /*
2376
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2377
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2378
- > return false;
2379
- > }
2380
- */
2381
- return true;
2382
- }
2383
- /**
2384
- * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2385
- * TODO: [🐠] Maybe base this on `makeValidator`
2386
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2387
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2388
- * - [🏍] ? Is context in each template
2389
- * - [♨] Are samples prepared
2390
- * - [♨] Are templates prepared
2391
- */
2392
-
2393
- /**
2394
- * Serializes an error into a [🚉] JSON-serializable object
2395
- *
2396
- * @public exported from `@promptbook/utils`
2397
- */
2398
- function serializeError(error) {
2399
- var name = error.name, message = error.message, stack = error.stack;
2400
- if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2401
- throw new UnexpectedError(spaceTrim(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2402
- }
2403
- return {
2404
- name: name,
2405
- message: message,
2406
- stack: stack,
2407
- };
2408
- }
2409
-
2410
- /**
2411
- * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2412
- *
2413
- * Note: Internal utility of `joinLlmExecutionTools` but exposed type
2414
- * @public exported from `@promptbook/types`
2415
- */
2416
- var MultipleLlmExecutionTools = /** @class */ (function () {
2417
- /**
2418
- * Gets array of execution tools in order of priority
2419
- */
2420
- function MultipleLlmExecutionTools() {
2421
- var llmExecutionTools = [];
2422
- for (var _i = 0; _i < arguments.length; _i++) {
2423
- llmExecutionTools[_i] = arguments[_i];
2424
- }
2425
- this.llmExecutionTools = llmExecutionTools;
1980
+ var MultipleLlmExecutionTools = /** @class */ (function () {
1981
+ /**
1982
+ * Gets array of execution tools in order of priority
1983
+ */
1984
+ function MultipleLlmExecutionTools() {
1985
+ var llmExecutionTools = [];
1986
+ for (var _i = 0; _i < arguments.length; _i++) {
1987
+ llmExecutionTools[_i] = arguments[_i];
1988
+ }
1989
+ this.llmExecutionTools = llmExecutionTools;
2426
1990
  }
2427
1991
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "title", {
2428
1992
  get: function () {
@@ -2699,79 +2263,258 @@ function joinLlmExecutionTools() {
2699
2263
  * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
2700
2264
  */
2701
2265
 
2266
+ 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"}];
2267
+
2702
2268
  /**
2703
- * Takes an item or an array of items and returns an array of items
2704
- *
2705
- * 1) Any item except array and undefined returns array with that one item (also null)
2706
- * 2) Undefined returns empty array
2707
- * 3) Array returns itself
2269
+ * This error indicates that the pipeline collection cannot be propperly loaded
2708
2270
  *
2709
- * @private internal utility
2271
+ * @public exported from `@promptbook/core`
2710
2272
  */
2711
- function arrayableToArray(input) {
2712
- if (input === undefined) {
2713
- return [];
2714
- }
2715
- if (input instanceof Array) {
2716
- return input;
2273
+ var CollectionError = /** @class */ (function (_super) {
2274
+ __extends(CollectionError, _super);
2275
+ function CollectionError(message) {
2276
+ var _this = _super.call(this, message) || this;
2277
+ _this.name = 'CollectionError';
2278
+ Object.setPrototypeOf(_this, CollectionError.prototype);
2279
+ return _this;
2717
2280
  }
2718
- return [input];
2719
- }
2281
+ return CollectionError;
2282
+ }(Error));
2720
2283
 
2721
2284
  /**
2722
- * Parses the given script and returns the list of all used variables that are not defined in the script
2285
+ * This error type indicates that you try to use a feature that is not available in the current environment
2723
2286
  *
2724
- * @param script from which to extract the variables
2725
- * @returns the list of variable names
2726
- * @throws {ParseError} if the script is invalid
2727
- * @public exported from `@promptbook/utils`
2287
+ * @public exported from `@promptbook/core`
2728
2288
  */
2729
- function extractVariables(script) {
2730
- var variables = new Set();
2731
- script = "(()=>{".concat(script, "})()");
2732
- try {
2733
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2734
- try {
2735
- eval(script);
2736
- }
2737
- catch (error) {
2738
- if (!(error instanceof ReferenceError)) {
2739
- throw error;
2740
- }
2741
- var undefinedName = error.message.split(' ')[0];
2742
- /*
2743
- Note: Parsing the error
2744
- [PipelineUrlError: thing is not defined]
2745
- */
2746
- if (!undefinedName) {
2747
- throw error;
2748
- }
2749
- if (script.includes(undefinedName + '(')) {
2750
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2751
- }
2752
- else {
2753
- variables.add(undefinedName);
2754
- script = "const ".concat(undefinedName, " = '';") + script;
2755
- }
2756
- }
2757
- }
2758
- catch (error) {
2759
- if (!(error instanceof Error)) {
2760
- throw error;
2761
- }
2762
- throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2289
+ var EnvironmentMismatchError = /** @class */ (function (_super) {
2290
+ __extends(EnvironmentMismatchError, _super);
2291
+ function EnvironmentMismatchError(message) {
2292
+ var _this = _super.call(this, message) || this;
2293
+ _this.name = 'EnvironmentMismatchError';
2294
+ Object.setPrototypeOf(_this, EnvironmentMismatchError.prototype);
2295
+ return _this;
2763
2296
  }
2764
- return variables;
2765
- }
2297
+ return EnvironmentMismatchError;
2298
+ }(Error));
2299
+
2766
2300
  /**
2767
- * TODO: [🔣] Support for multiple languages - python, java,...
2301
+ * This error occurs when some expectation is not met in the execution of the pipeline
2302
+ *
2303
+ * @public exported from `@promptbook/core`
2304
+ * Note: Do not throw this error, its reserved for `checkExpectations` and `createPipelineExecutor` and public ONLY to be serializable through remote server
2305
+ * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
2306
+ * Note: This is a kindof subtype of PipelineExecutionError
2768
2307
  */
2308
+ var ExpectError = /** @class */ (function (_super) {
2309
+ __extends(ExpectError, _super);
2310
+ function ExpectError(message) {
2311
+ var _this = _super.call(this, message) || this;
2312
+ _this.name = 'ExpectError';
2313
+ Object.setPrototypeOf(_this, ExpectError.prototype);
2314
+ return _this;
2315
+ }
2316
+ return ExpectError;
2317
+ }(Error));
2769
2318
 
2770
2319
  /**
2771
- * Parses the template and returns the set of all used parameters
2320
+ * This error type indicates that some limit was reached
2772
2321
  *
2773
- * @param template the template with used parameters
2774
- * @returns the set of parameter names
2322
+ * @public exported from `@promptbook/core`
2323
+ */
2324
+ var LimitReachedError = /** @class */ (function (_super) {
2325
+ __extends(LimitReachedError, _super);
2326
+ function LimitReachedError(message) {
2327
+ var _this = _super.call(this, message) || this;
2328
+ _this.name = 'LimitReachedError';
2329
+ Object.setPrototypeOf(_this, LimitReachedError.prototype);
2330
+ return _this;
2331
+ }
2332
+ return LimitReachedError;
2333
+ }(Error));
2334
+
2335
+ /**
2336
+ * This error type indicates that some part of the code is not implemented yet
2337
+ *
2338
+ * @public exported from `@promptbook/core`
2339
+ */
2340
+ var NotYetImplementedError = /** @class */ (function (_super) {
2341
+ __extends(NotYetImplementedError, _super);
2342
+ function NotYetImplementedError(message) {
2343
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This feature is not implemented yet but it will be soon.\n\n If you want speed up the implementation or just read more, look here:\n https://github.com/webgptorg/promptbook\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
2344
+ _this.name = 'NotYetImplementedError';
2345
+ Object.setPrototypeOf(_this, NotYetImplementedError.prototype);
2346
+ return _this;
2347
+ }
2348
+ return NotYetImplementedError;
2349
+ }(Error));
2350
+
2351
+ /**
2352
+ * Index of all custom errors
2353
+ *
2354
+ * @public exported from `@promptbook/core`
2355
+ */
2356
+ var ERRORS = {
2357
+ ExpectError: ExpectError,
2358
+ CollectionError: CollectionError,
2359
+ EnvironmentMismatchError: EnvironmentMismatchError,
2360
+ LimitReachedError: LimitReachedError,
2361
+ NotFoundError: NotFoundError,
2362
+ NotYetImplementedError: NotYetImplementedError,
2363
+ ParseError: ParseError,
2364
+ PipelineExecutionError: PipelineExecutionError,
2365
+ PipelineLogicError: PipelineLogicError,
2366
+ PipelineUrlError: PipelineUrlError,
2367
+ UnexpectedError: UnexpectedError,
2368
+ // TODO: [🪑]> VersionMismatchError,
2369
+ };
2370
+
2371
+ /**
2372
+ * Deserializes the error object
2373
+ *
2374
+ * @public exported from `@promptbook/utils`
2375
+ */
2376
+ function deserializeError(error) {
2377
+ if (error.name === 'Error') {
2378
+ return new Error(error.message);
2379
+ }
2380
+ var CustomError = ERRORS[error.name];
2381
+ return new CustomError(error.message);
2382
+ }
2383
+
2384
+ /**
2385
+ * Asserts that the execution of a Promptbook is successful
2386
+ *
2387
+ * @param executionResult - The partial result of the Promptbook execution
2388
+ * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2389
+ * @public exported from `@promptbook/core`
2390
+ */
2391
+ function assertsExecutionSuccessful(executionResult) {
2392
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2393
+ if (isSuccessful === true) {
2394
+ return;
2395
+ }
2396
+ if (errors.length === 0) {
2397
+ throw new PipelineExecutionError("Promptbook Execution failed because of unknown reason");
2398
+ }
2399
+ else if (errors.length === 1) {
2400
+ throw deserializeError(errors[0]);
2401
+ }
2402
+ else {
2403
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Multiple errors occurred during Promptbook execution\n\n ".concat(block(errors
2404
+ .map(function (_a, index) {
2405
+ var name = _a.name, stack = _a.stack, message = _a.message;
2406
+ return spaceTrim$1(function (block) { return "\n ".concat(name, " ").concat(index + 1, ":\n ").concat(block(stack || message), "\n "); });
2407
+ })
2408
+ .join('\n')), "\n "); }));
2409
+ }
2410
+ }
2411
+ /**
2412
+ * TODO: [🧠] Can this return type be better typed than void
2413
+ */
2414
+
2415
+ /**
2416
+ * Determine if the pipeline is fully prepared
2417
+ *
2418
+ * @public exported from `@promptbook/core`
2419
+ */
2420
+ function isPipelinePrepared(pipeline) {
2421
+ // Note: Ignoring `pipeline.preparations` @@@
2422
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2423
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2424
+ return false;
2425
+ }
2426
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2427
+ return false;
2428
+ }
2429
+ /*
2430
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2431
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2432
+ > return false;
2433
+ > }
2434
+ */
2435
+ return true;
2436
+ }
2437
+ /**
2438
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2439
+ * TODO: [🐠] Maybe base this on `makeValidator`
2440
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2441
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2442
+ * - [🏍] ? Is context in each template
2443
+ * - [♨] Are samples prepared
2444
+ * - [♨] Are templates prepared
2445
+ */
2446
+
2447
+ /**
2448
+ * Serializes an error into a [🚉] JSON-serializable object
2449
+ *
2450
+ * @public exported from `@promptbook/utils`
2451
+ */
2452
+ function serializeError(error) {
2453
+ var name = error.name, message = error.message, stack = error.stack;
2454
+ if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2455
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2456
+ }
2457
+ return {
2458
+ name: name,
2459
+ message: message,
2460
+ stack: stack,
2461
+ };
2462
+ }
2463
+
2464
+ /**
2465
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2466
+ *
2467
+ * @param script from which to extract the variables
2468
+ * @returns the list of variable names
2469
+ * @throws {ParseError} if the script is invalid
2470
+ * @public exported from `@promptbook/utils`
2471
+ */
2472
+ function extractVariables(script) {
2473
+ var variables = new Set();
2474
+ script = "(()=>{".concat(script, "})()");
2475
+ try {
2476
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2477
+ try {
2478
+ eval(script);
2479
+ }
2480
+ catch (error) {
2481
+ if (!(error instanceof ReferenceError)) {
2482
+ throw error;
2483
+ }
2484
+ var undefinedName = error.message.split(' ')[0];
2485
+ /*
2486
+ Note: Parsing the error
2487
+ [PipelineUrlError: thing is not defined]
2488
+ */
2489
+ if (!undefinedName) {
2490
+ throw error;
2491
+ }
2492
+ if (script.includes(undefinedName + '(')) {
2493
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2494
+ }
2495
+ else {
2496
+ variables.add(undefinedName);
2497
+ script = "const ".concat(undefinedName, " = '';") + script;
2498
+ }
2499
+ }
2500
+ }
2501
+ catch (error) {
2502
+ if (!(error instanceof Error)) {
2503
+ throw error;
2504
+ }
2505
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2506
+ }
2507
+ return variables;
2508
+ }
2509
+ /**
2510
+ * TODO: [🔣] Support for multiple languages - python, java,...
2511
+ */
2512
+
2513
+ /**
2514
+ * Parses the template and returns the set of all used parameters
2515
+ *
2516
+ * @param template the template with used parameters
2517
+ * @returns the set of parameter names
2775
2518
  * @throws {ParseError} if the script is invalid
2776
2519
  * @public exported from `@promptbook/utils`
2777
2520
  */
@@ -2825,7 +2568,7 @@ function extractParameterNamesFromTemplate(template) {
2825
2568
  // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2826
2569
  if (foreach !== undefined) {
2827
2570
  try {
2828
- for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2571
+ for (var _l = __values(foreach.inputSubparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2829
2572
  var subparameterName = _m.value;
2830
2573
  if (parameterNames.has(subparameterName)) {
2831
2574
  parameterNames.delete(subparameterName);
@@ -2940,6 +2683,42 @@ function TODO_USE() {
2940
2683
  }
2941
2684
  }
2942
2685
 
2686
+ /**
2687
+ * This error indicates problems parsing the format value
2688
+ *
2689
+ * For example, when the format value is not a valid JSON or CSV
2690
+ * This is not thrown directly but in extended classes
2691
+ *
2692
+ * @public exported from `@promptbook/core`
2693
+ */
2694
+ var AbstractFormatError = /** @class */ (function (_super) {
2695
+ __extends(AbstractFormatError, _super);
2696
+ // Note: To allow instanceof do not put here error `name`
2697
+ // public readonly name = 'AbstractFormatError';
2698
+ function AbstractFormatError(message) {
2699
+ var _this = _super.call(this, message) || this;
2700
+ Object.setPrototypeOf(_this, AbstractFormatError.prototype);
2701
+ return _this;
2702
+ }
2703
+ return AbstractFormatError;
2704
+ }(Error));
2705
+
2706
+ /**
2707
+ * This error indicates problem with parsing of CSV
2708
+ *
2709
+ * @public exported from `@promptbook/core`
2710
+ */
2711
+ var CsvFormatError = /** @class */ (function (_super) {
2712
+ __extends(CsvFormatError, _super);
2713
+ function CsvFormatError(message) {
2714
+ var _this = _super.call(this, message) || this;
2715
+ _this.name = 'CsvFormatError';
2716
+ Object.setPrototypeOf(_this, CsvFormatError.prototype);
2717
+ return _this;
2718
+ }
2719
+ return CsvFormatError;
2720
+ }(AbstractFormatError));
2721
+
2943
2722
  /**
2944
2723
  * @@@
2945
2724
  *
@@ -2947,7 +2726,7 @@ function TODO_USE() {
2947
2726
  */
2948
2727
  var MANDATORY_CSV_SETTINGS = Object.freeze({
2949
2728
  header: true,
2950
- // encoding: 'utf8',
2729
+ // encoding: 'utf-8',
2951
2730
  });
2952
2731
 
2953
2732
  /**
@@ -2960,7 +2739,7 @@ var CsvFormatDefinition = {
2960
2739
  formatName: 'CSV',
2961
2740
  aliases: ['SPREADSHEET', 'TABLE'],
2962
2741
  isValid: function (value, settings, schema) {
2963
- // TODO: !!!!!! Implement CSV validation
2742
+ // TODO: Implement CSV validation
2964
2743
  TODO_USE(value /* <- TODO: Use value here */);
2965
2744
  TODO_USE(settings /* <- TODO: Use settings here */);
2966
2745
  TODO_USE(schema /* <- TODO: Use schema here */);
@@ -2981,7 +2760,7 @@ var CsvFormatDefinition = {
2981
2760
  subvalueDefinitions: [
2982
2761
  {
2983
2762
  subvalueName: 'ROW',
2984
- mapValues: function (value, settings, mapCallback) {
2763
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
2985
2764
  return __awaiter(this, void 0, void 0, function () {
2986
2765
  var csv, mappedData;
2987
2766
  var _this = this;
@@ -2990,24 +2769,22 @@ var CsvFormatDefinition = {
2990
2769
  case 0:
2991
2770
  csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2992
2771
  if (csv.errors.length !== 0) {
2993
- throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2994
- spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2772
+ throw new CsvFormatError(spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2995
2773
  }
2996
2774
  return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2997
- var _a;
2998
- var _b;
2999
- return __generator(this, function (_c) {
3000
- switch (_c.label) {
2775
+ var _a, _b;
2776
+ var _c;
2777
+ return __generator(this, function (_d) {
2778
+ switch (_d.label) {
3001
2779
  case 0:
2780
+ if (row[outputParameterName]) {
2781
+ throw new CsvFormatError("Can not overwrite existing column \"".concat(outputParameterName, "\" in CSV row"));
2782
+ }
3002
2783
  _a = [__assign({}, row)];
3003
- _b = {};
3004
- // <- TODO: !!!!!! Dynamic new column name and position
3005
- // <- TODO: !!!!!! Check name collisions
2784
+ _c = {};
2785
+ _b = outputParameterName;
3006
2786
  return [4 /*yield*/, mapCallback(row, index)];
3007
- case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
3008
- // <- TODO: !!!!!! Dynamic new column name and position
3009
- // <- TODO: !!!!!! Check name collisions
3010
- _c.sent(), _b)])))];
2787
+ case 1: return [2 /*return*/, __assign.apply(void 0, _a.concat([(_c[_b] = _d.sent(), _c)]))];
3011
2788
  }
3012
2789
  });
3013
2790
  }); }))];
@@ -3021,7 +2798,7 @@ var CsvFormatDefinition = {
3021
2798
  },
3022
2799
  {
3023
2800
  subvalueName: 'CELL',
3024
- mapValues: function (value, settings, mapCallback) {
2801
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
3025
2802
  return __awaiter(this, void 0, void 0, function () {
3026
2803
  var csv, mappedData;
3027
2804
  var _this = this;
@@ -3030,8 +2807,7 @@ var CsvFormatDefinition = {
3030
2807
  case 0:
3031
2808
  csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3032
2809
  if (csv.errors.length !== 0) {
3033
- throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3034
- spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2810
+ throw new CsvFormatError(spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3035
2811
  }
3036
2812
  return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3037
2813
  var _this = this;
@@ -3148,7 +2924,7 @@ var TextFormatDefinition = {
3148
2924
  subvalueDefinitions: [
3149
2925
  {
3150
2926
  subvalueName: 'LINE',
3151
- mapValues: function (value, settings, mapCallback) {
2927
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
3152
2928
  return __awaiter(this, void 0, void 0, function () {
3153
2929
  var lines, mappedLines;
3154
2930
  return __generator(this, function (_a) {
@@ -3420,6 +3196,25 @@ function extractJsonBlock(markdown) {
3420
3196
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3421
3197
  */
3422
3198
 
3199
+ /**
3200
+ * Takes an item or an array of items and returns an array of items
3201
+ *
3202
+ * 1) Any item except array and undefined returns array with that one item (also null)
3203
+ * 2) Undefined returns empty array
3204
+ * 3) Array returns itself
3205
+ *
3206
+ * @private internal utility
3207
+ */
3208
+ function arrayableToArray(input) {
3209
+ if (input === undefined) {
3210
+ return [];
3211
+ }
3212
+ if (input instanceof Array) {
3213
+ return input;
3214
+ }
3215
+ return [input];
3216
+ }
3217
+
3423
3218
  /**
3424
3219
  * Just says that the variable is not used but should be kept
3425
3220
  * No side effects.
@@ -3585,69 +3380,330 @@ function countSentences(text) {
3585
3380
  return splitIntoSentences(text).length;
3586
3381
  }
3587
3382
 
3383
+ var defaultDiacriticsRemovalMap = [
3384
+ {
3385
+ base: 'A',
3386
+ letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
3387
+ },
3388
+ { base: 'AA', letters: '\uA732' },
3389
+ { base: 'AE', letters: '\u00C6\u01FC\u01E2' },
3390
+ { base: 'AO', letters: '\uA734' },
3391
+ { base: 'AU', letters: '\uA736' },
3392
+ { base: 'AV', letters: '\uA738\uA73A' },
3393
+ { base: 'AY', letters: '\uA73C' },
3394
+ {
3395
+ base: 'B',
3396
+ letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
3397
+ },
3398
+ {
3399
+ base: 'C',
3400
+ letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
3401
+ },
3402
+ {
3403
+ base: 'D',
3404
+ letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
3405
+ },
3406
+ { base: 'DZ', letters: '\u01F1\u01C4' },
3407
+ { base: 'Dz', letters: '\u01F2\u01C5' },
3408
+ {
3409
+ base: 'E',
3410
+ letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E',
3411
+ },
3412
+ { base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
3413
+ {
3414
+ base: 'G',
3415
+ letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
3416
+ },
3417
+ {
3418
+ base: 'H',
3419
+ letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
3420
+ },
3421
+ {
3422
+ base: 'I',
3423
+ letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
3424
+ },
3425
+ { base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
3426
+ {
3427
+ base: 'K',
3428
+ letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
3429
+ },
3430
+ {
3431
+ base: 'L',
3432
+ letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
3433
+ },
3434
+ { base: 'LJ', letters: '\u01C7' },
3435
+ { base: 'Lj', letters: '\u01C8' },
3436
+ { base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
3437
+ {
3438
+ base: 'N',
3439
+ letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
3440
+ },
3441
+ { base: 'NJ', letters: '\u01CA' },
3442
+ { base: 'Nj', letters: '\u01CB' },
3443
+ {
3444
+ base: 'O',
3445
+ letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C',
3446
+ },
3447
+ { base: 'OI', letters: '\u01A2' },
3448
+ { base: 'OO', letters: '\uA74E' },
3449
+ { base: 'OU', letters: '\u0222' },
3450
+ { base: 'OE', letters: '\u008C\u0152' },
3451
+ { base: 'oe', letters: '\u009C\u0153' },
3452
+ {
3453
+ base: 'P',
3454
+ letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
3455
+ },
3456
+ { base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
3457
+ {
3458
+ base: 'R',
3459
+ letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
3460
+ },
3461
+ {
3462
+ base: 'S',
3463
+ letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
3464
+ },
3465
+ {
3466
+ base: 'T',
3467
+ letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
3468
+ },
3469
+ { base: 'TZ', letters: '\uA728' },
3470
+ {
3471
+ base: 'U',
3472
+ letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
3473
+ },
3474
+ { base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
3475
+ { base: 'VY', letters: '\uA760' },
3476
+ {
3477
+ base: 'W',
3478
+ letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
3479
+ },
3480
+ { base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
3481
+ {
3482
+ base: 'Y',
3483
+ letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
3484
+ },
3485
+ {
3486
+ base: 'Z',
3487
+ letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
3488
+ },
3489
+ {
3490
+ base: 'a',
3491
+ letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250',
3492
+ },
3493
+ { base: 'aa', letters: '\uA733' },
3494
+ { base: 'ae', letters: '\u00E6\u01FD\u01E3' },
3495
+ { base: 'ao', letters: '\uA735' },
3496
+ { base: 'au', letters: '\uA737' },
3497
+ { base: 'av', letters: '\uA739\uA73B' },
3498
+ { base: 'ay', letters: '\uA73D' },
3499
+ {
3500
+ base: 'b',
3501
+ letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
3502
+ },
3503
+ {
3504
+ base: 'c',
3505
+ letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184',
3506
+ },
3507
+ {
3508
+ base: 'd',
3509
+ letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
3510
+ },
3511
+ { base: 'dz', letters: '\u01F3\u01C6' },
3512
+ {
3513
+ base: 'e',
3514
+ letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
3515
+ },
3516
+ { base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
3517
+ {
3518
+ base: 'g',
3519
+ letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
3520
+ },
3521
+ {
3522
+ base: 'h',
3523
+ letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
3524
+ },
3525
+ { base: 'hv', letters: '\u0195' },
3526
+ {
3527
+ base: 'i',
3528
+ letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131',
3529
+ },
3530
+ { base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
3531
+ {
3532
+ base: 'k',
3533
+ letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
3534
+ },
3535
+ {
3536
+ base: 'l',
3537
+ letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
3538
+ },
3539
+ { base: 'lj', letters: '\u01C9' },
3540
+ { base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
3541
+ {
3542
+ base: 'n',
3543
+ letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
3544
+ },
3545
+ { base: 'nj', letters: '\u01CC' },
3546
+ {
3547
+ base: 'o',
3548
+ letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275',
3549
+ },
3550
+ { base: 'oi', letters: '\u01A3' },
3551
+ { base: 'ou', letters: '\u0223' },
3552
+ { base: 'oo', letters: '\uA74F' },
3553
+ {
3554
+ base: 'p',
3555
+ letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
3556
+ },
3557
+ { base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
3558
+ {
3559
+ base: 'r',
3560
+ letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
3561
+ },
3562
+ {
3563
+ base: 's',
3564
+ letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
3565
+ },
3566
+ {
3567
+ base: 't',
3568
+ letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
3569
+ },
3570
+ { base: 'tz', letters: '\uA729' },
3571
+ {
3572
+ base: 'u',
3573
+ letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289',
3574
+ },
3575
+ { base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
3576
+ { base: 'vy', letters: '\uA761' },
3577
+ {
3578
+ base: 'w',
3579
+ letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
3580
+ },
3581
+ { base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
3582
+ {
3583
+ base: 'y',
3584
+ letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
3585
+ },
3586
+ {
3587
+ base: 'z',
3588
+ letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
3589
+ },
3590
+ ];
3588
3591
  /**
3589
- * Counts number of words in the text
3590
- *
3591
- * @public exported from `@promptbook/utils`
3592
- */
3593
- function countWords(text) {
3594
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3595
- text = removeDiacritics(text);
3596
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3597
- }
3598
-
3599
- /**
3600
- * Index of all counter functions
3601
- *
3602
- * @public exported from `@promptbook/utils`
3603
- */
3604
- var CountUtils = {
3605
- CHARACTERS: countCharacters,
3606
- WORDS: countWords,
3607
- SENTENCES: countSentences,
3608
- PARAGRAPHS: countParagraphs,
3609
- LINES: countLines,
3610
- PAGES: countPages,
3611
- };
3612
- /**
3613
- * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3614
- */
3615
-
3616
- /**
3617
- * Function checkExpectations will check if the expectations on given value are met
3592
+ * Map of letters from diacritic variant to diacritless variant
3593
+ * Contains lowercase and uppercase separatelly
3618
3594
  *
3619
- * Note: There are two simmilar functions:
3620
- * - `checkExpectations` which throws an error if the expectations are not met
3621
- * - `isPassingExpectations` which returns a boolean
3595
+ * > "á" => "a"
3596
+ * > "ě" => "e"
3597
+ * > "Ă" => "A"
3598
+ * > ...
3622
3599
  *
3623
- * @throws {ExpectError} if the expectations are not met
3624
- * @returns {void} Nothing
3625
- * @private internal function of `createPipelineExecutor`
3600
+ * @public exported from `@promptbook/utils`
3626
3601
  */
3627
- function checkExpectations(expectations, value) {
3628
- var e_1, _a;
3629
- try {
3630
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3631
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3632
- var amount = CountUtils[unit.toUpperCase()](value);
3633
- if (min && amount < min) {
3634
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3635
- } /* not else */
3636
- if (max && amount > max) {
3637
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3638
- }
3639
- }
3640
- }
3641
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3642
- finally {
3643
- try {
3644
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3645
- }
3646
- finally { if (e_1) throw e_1.error; }
3602
+ var DIACRITIC_VARIANTS_LETTERS = {};
3603
+ // tslint:disable-next-line: prefer-for-of
3604
+ for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
3605
+ var letters = defaultDiacriticsRemovalMap[i].letters;
3606
+ // tslint:disable-next-line: prefer-for-of
3607
+ for (var j = 0; j < letters.length; j++) {
3608
+ DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
3647
3609
  }
3648
3610
  }
3649
- /**
3650
- * Function checkExpectations will check if the expectations on given value are met
3611
+ // <- TODO: [🍓] Put to maker function to save execution time if not needed
3612
+ /*
3613
+ @see https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
3614
+ Licensed under the Apache License, Version 2.0 (the "License");
3615
+ you may not use this file except in compliance with the License.
3616
+ You may obtain a copy of the License at
3617
+
3618
+ http://www.apache.org/licenses/LICENSE-2.0
3619
+
3620
+ Unless required by applicable law or agreed to in writing, software
3621
+ distributed under the License is distributed on an "AS IS" BASIS,
3622
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3623
+ See the License for the specific language governing permissions and
3624
+ limitations under the License.
3625
+ */
3626
+
3627
+ /**
3628
+ * @@@
3629
+ *
3630
+ * @param input @@@
3631
+ * @returns @@@
3632
+ * @public exported from `@promptbook/utils`
3633
+ */
3634
+ function removeDiacritics(input) {
3635
+ /*eslint no-control-regex: "off"*/
3636
+ return input.replace(/[^\u0000-\u007E]/g, function (a) {
3637
+ return DIACRITIC_VARIANTS_LETTERS[a] || a;
3638
+ });
3639
+ }
3640
+ /**
3641
+ * TODO: [Ж] Variant for cyrillic (and in general non-latin) letters
3642
+ */
3643
+
3644
+ /**
3645
+ * Counts number of words in the text
3646
+ *
3647
+ * @public exported from `@promptbook/utils`
3648
+ */
3649
+ function countWords(text) {
3650
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3651
+ text = removeDiacritics(text);
3652
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3653
+ }
3654
+
3655
+ /**
3656
+ * Index of all counter functions
3657
+ *
3658
+ * @public exported from `@promptbook/utils`
3659
+ */
3660
+ var CountUtils = {
3661
+ CHARACTERS: countCharacters,
3662
+ WORDS: countWords,
3663
+ SENTENCES: countSentences,
3664
+ PARAGRAPHS: countParagraphs,
3665
+ LINES: countLines,
3666
+ PAGES: countPages,
3667
+ };
3668
+ /**
3669
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3670
+ */
3671
+
3672
+ /**
3673
+ * Function checkExpectations will check if the expectations on given value are met
3674
+ *
3675
+ * Note: There are two simmilar functions:
3676
+ * - `checkExpectations` which throws an error if the expectations are not met
3677
+ * - `isPassingExpectations` which returns a boolean
3678
+ *
3679
+ * @throws {ExpectError} if the expectations are not met
3680
+ * @returns {void} Nothing
3681
+ * @private internal function of `createPipelineExecutor`
3682
+ */
3683
+ function checkExpectations(expectations, value) {
3684
+ var e_1, _a;
3685
+ try {
3686
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3687
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3688
+ var amount = CountUtils[unit.toUpperCase()](value);
3689
+ if (min && amount < min) {
3690
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3691
+ } /* not else */
3692
+ if (max && amount > max) {
3693
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3694
+ }
3695
+ }
3696
+ }
3697
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3698
+ finally {
3699
+ try {
3700
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3701
+ }
3702
+ finally { if (e_1) throw e_1.error; }
3703
+ }
3704
+ }
3705
+ /**
3706
+ * Function checkExpectations will check if the expectations on given value are met
3651
3707
  *
3652
3708
  * Note: There are two simmilar functions:
3653
3709
  * - `checkExpectations` which throws an error if the expectations are not met
@@ -3681,11 +3737,11 @@ function isPassingExpectations(expectations, value) {
3681
3737
  */
3682
3738
  function executeAttempts(options) {
3683
3739
  return __awaiter(this, void 0, void 0, function () {
3684
- var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3740
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _llms, llmTools, _loop_1, attempt, state_1;
3685
3741
  return __generator(this, function (_a) {
3686
3742
  switch (_a.label) {
3687
3743
  case 0:
3688
- 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;
3744
+ jokerParameterNames = options.jokerParameterNames, priority = options.priority, maxAttempts = options.maxAttempts, preparedContent = options.preparedContent, parameters = options.parameters, template = options.template, preparedPipeline = options.preparedPipeline, tools = options.tools, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3689
3745
  maxExecutionAttempts = settings.maxExecutionAttempts;
3690
3746
  $ongoingTemplateResult = {
3691
3747
  $result: null,
@@ -3693,6 +3749,8 @@ function executeAttempts(options) {
3693
3749
  $expectError: null,
3694
3750
  $scriptPipelineExecutionErrors: [],
3695
3751
  };
3752
+ _llms = arrayableToArray(tools.llm);
3753
+ llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(_llms), false));
3696
3754
  _loop_1 = function (attempt) {
3697
3755
  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;
3698
3756
  var e_1, _q, e_3, _r, e_2, _s;
@@ -3738,7 +3796,9 @@ function executeAttempts(options) {
3738
3796
  title: template.title,
3739
3797
  pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3740
3798
  ? preparedPipeline.pipelineUrl
3741
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3799
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name
3800
+ // <- TODO: Here should be maybe also subformat index to distinguish between same template with different subformat values
3801
+ ),
3742
3802
  parameters: parameters,
3743
3803
  content: preparedContent,
3744
3804
  modelRequirements: modelRequirements,
@@ -3759,7 +3819,9 @@ function executeAttempts(options) {
3759
3819
  return [3 /*break*/, 9];
3760
3820
  case 4:
3761
3821
  _d = $ongoingTemplateResult;
3762
- return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3822
+ return [4 /*yield*/, llmTools.callChatModel(
3823
+ // <- TODO: [🧁] Check that `callChatModel` is defined
3824
+ $deepFreeze($ongoingTemplateResult.$prompt))];
3763
3825
  case 5:
3764
3826
  _d.$chatResult = _t.sent();
3765
3827
  // TODO: [🍬] Destroy chatThread
@@ -3768,7 +3830,9 @@ function executeAttempts(options) {
3768
3830
  return [3 /*break*/, 10];
3769
3831
  case 6:
3770
3832
  _e = $ongoingTemplateResult;
3771
- return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3833
+ return [4 /*yield*/, llmTools.callCompletionModel(
3834
+ // <- TODO: [🧁] Check that `callCompletionModel` is defined
3835
+ $deepFreeze($ongoingTemplateResult.$prompt))];
3772
3836
  case 7:
3773
3837
  _e.$completionResult = _t.sent();
3774
3838
  $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
@@ -4042,7 +4106,7 @@ function executeAttempts(options) {
4042
4106
  *
4043
4107
  * @private internal utility of `createPipelineExecutor`
4044
4108
  */
4045
- function executeFormatCells(options) {
4109
+ function executeFormatSubvalues(options) {
4046
4110
  return __awaiter(this, void 0, void 0, function () {
4047
4111
  var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
4048
4112
  var _this = this;
@@ -4080,18 +4144,18 @@ function executeFormatCells(options) {
4080
4144
  }
4081
4145
  if (formatDefinition.formatName === 'CSV') {
4082
4146
  formatSettings = settings.csvSettings;
4083
- // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4147
+ // <- TODO: [🤹‍♂️] More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4084
4148
  }
4085
- return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4149
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, template.foreach.outputSubparameterName, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4086
4150
  var mappedParameters, allSubparameters, subresultString;
4087
4151
  return __generator(this, function (_a) {
4088
4152
  switch (_a.label) {
4089
4153
  case 0:
4090
- // TODO: !!!!!!! Limit to N concurrent executions
4091
- // TODO: !!!!!!! Report progress
4154
+ // TODO: [🤹‍♂️][🪂] Limit to N concurrent executions
4155
+ // TODO: When done [🐚] Report progress also for each subvalue here
4092
4156
  try {
4093
4157
  mappedParameters = mapAvailableToExpectedParameters({
4094
- expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4158
+ expectedParameters: Object.fromEntries(template.foreach.inputSubparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4095
4159
  availableParameters: subparameters,
4096
4160
  });
4097
4161
  }
@@ -4099,12 +4163,12 @@ function executeFormatCells(options) {
4099
4163
  if (!(error instanceof PipelineExecutionError)) {
4100
4164
  throw error;
4101
4165
  }
4102
- throw new PipelineExecutionError(spaceTrim(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 "); }));
4166
+ throw new PipelineExecutionError(spaceTrim(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 Subparameter index: ").concat(index, "\n "); }));
4103
4167
  }
4104
4168
  allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4105
4169
  // 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
4106
4170
  Object.freeze(allSubparameters);
4107
- return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4171
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }) }))];
4108
4172
  case 1:
4109
4173
  subresultString = _a.sent();
4110
4174
  return [2 /*return*/, subresultString];
@@ -4118,10 +4182,6 @@ function executeFormatCells(options) {
4118
4182
  });
4119
4183
  });
4120
4184
  }
4121
- /**
4122
- * TODO: !!!!!! Make pipelineIdentification more precise
4123
- * TODO: !!!!!! How FOREACH execution looks in the report
4124
- */
4125
4185
 
4126
4186
  /**
4127
4187
  * @@@
@@ -4236,12 +4296,12 @@ function getReservedParametersForTemplate(options) {
4236
4296
  */
4237
4297
  function executeTemplate(options) {
4238
4298
  return __awaiter(this, void 0, void 0, function () {
4239
- 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;
4299
+ var currentTemplate, preparedPipeline, parametersToPass, tools, 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;
4240
4300
  var e_1, _f, _g;
4241
4301
  return __generator(this, function (_h) {
4242
4302
  switch (_h.label) {
4243
4303
  case 0:
4244
- 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;
4304
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, onProgress = options.onProgress, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
4245
4305
  maxExecutionAttempts = settings.maxExecutionAttempts;
4246
4306
  name = "pipeline-executor-frame-".concat(currentTemplate.name);
4247
4307
  title = currentTemplate.title;
@@ -4315,7 +4375,7 @@ function executeTemplate(options) {
4315
4375
  preparedContent = (currentTemplate.preparedContent || '{content}')
4316
4376
  .split('{content}')
4317
4377
  .join(currentTemplate.content);
4318
- return [4 /*yield*/, executeFormatCells({
4378
+ return [4 /*yield*/, executeFormatSubvalues({
4319
4379
  jokerParameterNames: jokerParameterNames,
4320
4380
  priority: priority,
4321
4381
  maxAttempts: maxAttempts,
@@ -4324,7 +4384,6 @@ function executeTemplate(options) {
4324
4384
  template: currentTemplate,
4325
4385
  preparedPipeline: preparedPipeline,
4326
4386
  tools: tools,
4327
- llmTools: llmTools,
4328
4387
  settings: settings,
4329
4388
  $executionReport: $executionReport,
4330
4389
  pipelineIdentification: pipelineIdentification,
@@ -4355,6 +4414,9 @@ function executeTemplate(options) {
4355
4414
  /**
4356
4415
  * TODO: [🤹‍♂️]
4357
4416
  */
4417
+ /**
4418
+ * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4419
+ */
4358
4420
 
4359
4421
  /**
4360
4422
  * @@@
@@ -4403,25 +4465,24 @@ function filterJustOutputParameters(options) {
4403
4465
  */
4404
4466
  function executePipeline(options) {
4405
4467
  return __awaiter(this, void 0, void 0, function () {
4406
- 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;
4407
- var e_1, _e, e_2, _f;
4408
- return __generator(this, function (_g) {
4409
- switch (_g.label) {
4468
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, rootDirname, _a, isVerbose, preparedPipeline, errors, warnings, executionReport, isReturned, _b, _c, parameter, e_1_1, _loop_1, _d, _e, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
4469
+ var e_1, _f, e_2, _g;
4470
+ return __generator(this, function (_h) {
4471
+ switch (_h.label) {
4410
4472
  case 0:
4411
4473
  inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4412
- maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4474
+ maxParallelCount = settings.maxParallelCount, rootDirname = settings.rootDirname, _a = settings.isVerbose, isVerbose = _a === void 0 ? IS_VERBOSE : _a;
4413
4475
  preparedPipeline = options.preparedPipeline;
4414
- llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
4415
4476
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
4416
- return [4 /*yield*/, preparePipeline(pipeline, {
4417
- llmTools: llmTools,
4477
+ return [4 /*yield*/, preparePipeline(pipeline, tools, {
4478
+ rootDirname: rootDirname,
4418
4479
  isVerbose: isVerbose,
4419
4480
  maxParallelCount: maxParallelCount,
4420
4481
  })];
4421
4482
  case 1:
4422
- preparedPipeline = _g.sent();
4483
+ preparedPipeline = _h.sent();
4423
4484
  setPreparedPipeline(preparedPipeline);
4424
- _g.label = 2;
4485
+ _h.label = 2;
4425
4486
  case 2:
4426
4487
  errors = [];
4427
4488
  warnings = [];
@@ -4434,17 +4495,17 @@ function executePipeline(options) {
4434
4495
  promptExecutions: [],
4435
4496
  };
4436
4497
  isReturned = false;
4437
- _g.label = 3;
4498
+ _h.label = 3;
4438
4499
  case 3:
4439
- _g.trys.push([3, 9, 10, 11]);
4440
- _a = __values(preparedPipeline.parameters.filter(function (_a) {
4500
+ _h.trys.push([3, 9, 10, 11]);
4501
+ _b = __values(preparedPipeline.parameters.filter(function (_a) {
4441
4502
  var isInput = _a.isInput;
4442
4503
  return isInput;
4443
- })), _b = _a.next();
4444
- _g.label = 4;
4504
+ })), _c = _b.next();
4505
+ _h.label = 4;
4445
4506
  case 4:
4446
- if (!!_b.done) return [3 /*break*/, 8];
4447
- parameter = _b.value;
4507
+ if (!!_c.done) return [3 /*break*/, 8];
4508
+ parameter = _c.value;
4448
4509
  if (!(inputParameters[parameter.name] === undefined)) return [3 /*break*/, 7];
4449
4510
  isReturned = true;
4450
4511
  if (!(onProgress !== undefined)) return [3 /*break*/, 6];
@@ -4452,8 +4513,8 @@ function executePipeline(options) {
4452
4513
  return [4 /*yield*/, forTime(IMMEDIATE_TIME)];
4453
4514
  case 5:
4454
4515
  // Note: Wait a short time to prevent race conditions
4455
- _g.sent();
4456
- _g.label = 6;
4516
+ _h.sent();
4517
+ _h.label = 6;
4457
4518
  case 6: return [2 /*return*/, $asDeeplyFrozenSerializableJson("Unuccessful PipelineExecutorResult (with missing parameter {".concat(parameter.name, "}) PipelineExecutorResult"), {
4458
4519
  isSuccessful: false,
4459
4520
  errors: __spreadArray([
@@ -4466,24 +4527,24 @@ function executePipeline(options) {
4466
4527
  preparedPipeline: preparedPipeline,
4467
4528
  })];
4468
4529
  case 7:
4469
- _b = _a.next();
4530
+ _c = _b.next();
4470
4531
  return [3 /*break*/, 4];
4471
4532
  case 8: return [3 /*break*/, 11];
4472
4533
  case 9:
4473
- e_1_1 = _g.sent();
4534
+ e_1_1 = _h.sent();
4474
4535
  e_1 = { error: e_1_1 };
4475
4536
  return [3 /*break*/, 11];
4476
4537
  case 10:
4477
4538
  try {
4478
- if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
4539
+ if (_c && !_c.done && (_f = _b.return)) _f.call(_b);
4479
4540
  }
4480
4541
  finally { if (e_1) throw e_1.error; }
4481
4542
  return [7 /*endfinally*/];
4482
4543
  case 11:
4483
4544
  _loop_1 = function (parameterName) {
4484
4545
  var parameter;
4485
- return __generator(this, function (_h) {
4486
- switch (_h.label) {
4546
+ return __generator(this, function (_j) {
4547
+ switch (_j.label) {
4487
4548
  case 0:
4488
4549
  parameter = preparedPipeline.parameters.find(function (_a) {
4489
4550
  var name = _a.name;
@@ -4500,8 +4561,8 @@ function executePipeline(options) {
4500
4561
  return [4 /*yield*/, forTime(IMMEDIATE_TIME)];
4501
4562
  case 2:
4502
4563
  // Note: Wait a short time to prevent race conditions
4503
- _h.sent();
4504
- _h.label = 3;
4564
+ _j.sent();
4565
+ _j.label = 3;
4505
4566
  case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4506
4567
  isSuccessful: false,
4507
4568
  errors: __spreadArray([
@@ -4517,39 +4578,39 @@ function executePipeline(options) {
4517
4578
  }
4518
4579
  });
4519
4580
  };
4520
- _g.label = 12;
4581
+ _h.label = 12;
4521
4582
  case 12:
4522
- _g.trys.push([12, 17, 18, 19]);
4523
- _c = __values(Object.keys(inputParameters)), _d = _c.next();
4524
- _g.label = 13;
4583
+ _h.trys.push([12, 17, 18, 19]);
4584
+ _d = __values(Object.keys(inputParameters)), _e = _d.next();
4585
+ _h.label = 13;
4525
4586
  case 13:
4526
- if (!!_d.done) return [3 /*break*/, 16];
4527
- parameterName = _d.value;
4587
+ if (!!_e.done) return [3 /*break*/, 16];
4588
+ parameterName = _e.value;
4528
4589
  return [5 /*yield**/, _loop_1(parameterName)];
4529
4590
  case 14:
4530
- state_1 = _g.sent();
4591
+ state_1 = _h.sent();
4531
4592
  if (typeof state_1 === "object")
4532
4593
  return [2 /*return*/, state_1.value];
4533
- _g.label = 15;
4594
+ _h.label = 15;
4534
4595
  case 15:
4535
- _d = _c.next();
4596
+ _e = _d.next();
4536
4597
  return [3 /*break*/, 13];
4537
4598
  case 16: return [3 /*break*/, 19];
4538
4599
  case 17:
4539
- e_2_1 = _g.sent();
4600
+ e_2_1 = _h.sent();
4540
4601
  e_2 = { error: e_2_1 };
4541
4602
  return [3 /*break*/, 19];
4542
4603
  case 18:
4543
4604
  try {
4544
- if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
4605
+ if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
4545
4606
  }
4546
4607
  finally { if (e_2) throw e_2.error; }
4547
4608
  return [7 /*endfinally*/];
4548
4609
  case 19:
4549
4610
  parametersToPass = inputParameters;
4550
- _g.label = 20;
4611
+ _h.label = 20;
4551
4612
  case 20:
4552
- _g.trys.push([20, 25, , 28]);
4613
+ _h.trys.push([20, 25, , 28]);
4553
4614
  resovedParameterNames_1 = preparedPipeline.parameters
4554
4615
  .filter(function (_a) {
4555
4616
  var isInput = _a.isInput;
@@ -4564,8 +4625,8 @@ function executePipeline(options) {
4564
4625
  loopLimit = LOOP_LIMIT;
4565
4626
  _loop_2 = function () {
4566
4627
  var currentTemplate, work_1;
4567
- return __generator(this, function (_j) {
4568
- switch (_j.label) {
4628
+ return __generator(this, function (_k) {
4629
+ switch (_k.label) {
4569
4630
  case 0:
4570
4631
  if (loopLimit-- < 0) {
4571
4632
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
@@ -4591,7 +4652,7 @@ function executePipeline(options) {
4591
4652
  if (!!currentTemplate) return [3 /*break*/, 3];
4592
4653
  /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4593
4654
  case 2:
4594
- /* [🤹‍♂️] */ _j.sent();
4655
+ /* [🤹‍♂️] */ _k.sent();
4595
4656
  return [3 /*break*/, 4];
4596
4657
  case 3:
4597
4658
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
@@ -4600,7 +4661,6 @@ function executePipeline(options) {
4600
4661
  preparedPipeline: preparedPipeline,
4601
4662
  parametersToPass: parametersToPass,
4602
4663
  tools: tools,
4603
- llmTools: llmTools,
4604
4664
  onProgress: function (progress) {
4605
4665
  if (isReturned) {
4606
4666
  throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
@@ -4614,7 +4674,7 @@ function executePipeline(options) {
4614
4674
  },
4615
4675
  settings: settings,
4616
4676
  $executionReport: executionReport,
4617
- pipelineIdentification: pipelineIdentification,
4677
+ pipelineIdentification: spaceTrim$1(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4618
4678
  })
4619
4679
  .then(function (newParametersToPass) {
4620
4680
  parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
@@ -4626,24 +4686,24 @@ function executePipeline(options) {
4626
4686
  // <- Note: Errors are catched here [3]
4627
4687
  // 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
4628
4688
  resolving_1.push(work_1);
4629
- _j.label = 4;
4689
+ _k.label = 4;
4630
4690
  case 4: return [2 /*return*/];
4631
4691
  }
4632
4692
  });
4633
4693
  };
4634
- _g.label = 21;
4694
+ _h.label = 21;
4635
4695
  case 21:
4636
4696
  if (!(unresovedTemplates_1.length > 0)) return [3 /*break*/, 23];
4637
4697
  return [5 /*yield**/, _loop_2()];
4638
4698
  case 22:
4639
- _g.sent();
4699
+ _h.sent();
4640
4700
  return [3 /*break*/, 21];
4641
4701
  case 23: return [4 /*yield*/, Promise.all(resolving_1)];
4642
4702
  case 24:
4643
- _g.sent();
4703
+ _h.sent();
4644
4704
  return [3 /*break*/, 28];
4645
4705
  case 25:
4646
- error_1 = _g.sent();
4706
+ error_1 = _h.sent();
4647
4707
  if (!(error_1 instanceof Error)) {
4648
4708
  throw error_1;
4649
4709
  }
@@ -4663,8 +4723,8 @@ function executePipeline(options) {
4663
4723
  return [4 /*yield*/, forTime(IMMEDIATE_TIME)];
4664
4724
  case 26:
4665
4725
  // Note: Wait a short time to prevent race conditions
4666
- _g.sent();
4667
- _g.label = 27;
4726
+ _h.sent();
4727
+ _h.label = 27;
4668
4728
  case 27: return [2 /*return*/, $asDeeplyFrozenSerializableJson('Unuccessful PipelineExecutorResult (with misc errors) PipelineExecutorResult', {
4669
4729
  isSuccessful: false,
4670
4730
  errors: __spreadArray([error_1], __read(errors), false).map(serializeError),
@@ -4691,8 +4751,8 @@ function executePipeline(options) {
4691
4751
  return [4 /*yield*/, forTime(IMMEDIATE_TIME)];
4692
4752
  case 29:
4693
4753
  // Note: Wait a short time to prevent race conditions
4694
- _g.sent();
4695
- _g.label = 30;
4754
+ _h.sent();
4755
+ _h.label = 30;
4696
4756
  case 30: return [2 /*return*/, $asDeeplyFrozenSerializableJson('Successful PipelineExecutorResult', {
4697
4757
  isSuccessful: true,
4698
4758
  errors: errors.map(serializeError),
@@ -4706,200 +4766,751 @@ function executePipeline(options) {
4706
4766
  });
4707
4767
  });
4708
4768
  }
4769
+ /**
4770
+ * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4771
+ */
4772
+
4773
+ /**
4774
+ * Creates executor function from pipeline and execution tools.
4775
+ *
4776
+ * @returns The executor function
4777
+ * @throws {PipelineLogicError} on logical error in the pipeline
4778
+ * @public exported from `@promptbook/core`
4779
+ */
4780
+ function createPipelineExecutor(options) {
4781
+ var _this = this;
4782
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4783
+ 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, _g = settings.rootDirname, rootDirname = _g === void 0 ? null : _g;
4784
+ validatePipeline(pipeline);
4785
+ var pipelineIdentification = (function () {
4786
+ // Note: This is a 😐 implementation of [🚞]
4787
+ var _ = [];
4788
+ if (pipeline.sourceFile !== undefined) {
4789
+ _.push("File: ".concat(pipeline.sourceFile));
4790
+ }
4791
+ if (pipeline.pipelineUrl !== undefined) {
4792
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4793
+ }
4794
+ return _.join('\n');
4795
+ })();
4796
+ var preparedPipeline;
4797
+ if (isPipelinePrepared(pipeline)) {
4798
+ preparedPipeline = pipeline;
4799
+ }
4800
+ else if (isNotPreparedWarningSupressed !== true) {
4801
+ console.warn(spaceTrim$1(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4802
+ }
4803
+ var runCount = 0;
4804
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4805
+ return __generator(this, function (_a) {
4806
+ runCount++;
4807
+ return [2 /*return*/, /* not await */ executePipeline({
4808
+ pipeline: pipeline,
4809
+ preparedPipeline: preparedPipeline,
4810
+ setPreparedPipeline: function (newPreparedPipeline) {
4811
+ preparedPipeline = newPreparedPipeline;
4812
+ },
4813
+ inputParameters: inputParameters,
4814
+ tools: tools,
4815
+ onProgress: onProgress,
4816
+ pipelineIdentification: spaceTrim$1(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4817
+ settings: {
4818
+ maxExecutionAttempts: maxExecutionAttempts,
4819
+ maxParallelCount: maxParallelCount,
4820
+ csvSettings: csvSettings,
4821
+ isVerbose: isVerbose,
4822
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4823
+ rootDirname: rootDirname,
4824
+ },
4825
+ })];
4826
+ });
4827
+ }); };
4828
+ return pipelineExecutor;
4829
+ }
4830
+ /**
4831
+ * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4832
+ */
4833
+
4834
+ /**
4835
+ * Prepares the persona for the pipeline
4836
+ *
4837
+ * @see https://github.com/webgptorg/promptbook/discussions/22
4838
+ * @public exported from `@promptbook/core`
4839
+ */
4840
+ function preparePersona(personaDescription, tools, options) {
4841
+ return __awaiter(this, void 0, void 0, function () {
4842
+ var _a, isVerbose, collection, preparePersonaExecutor, _b, _llms, llmTools, availableModels, availableModelNames, result, outputParameters, modelRequirementsRaw, modelRequirements, modelName, systemMessage, temperature;
4843
+ var _c;
4844
+ return __generator(this, function (_d) {
4845
+ switch (_d.label) {
4846
+ case 0:
4847
+ _a = options.isVerbose, isVerbose = _a === void 0 ? IS_VERBOSE : _a;
4848
+ if (tools === undefined || tools.llm === undefined) {
4849
+ throw new MissingToolsError('LLM tools are required for preparing persona');
4850
+ }
4851
+ collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
4852
+ _b = createPipelineExecutor;
4853
+ _c = {};
4854
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-persona.ptbk.md')];
4855
+ case 1:
4856
+ preparePersonaExecutor = _b.apply(void 0, [(_c.pipeline = _d.sent(),
4857
+ _c.tools = tools,
4858
+ _c)]);
4859
+ _llms = arrayableToArray(tools.llm);
4860
+ llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(_llms), false));
4861
+ return [4 /*yield*/, llmTools.listModels()];
4862
+ case 2:
4863
+ availableModels = _d.sent();
4864
+ availableModelNames = availableModels
4865
+ .filter(function (_a) {
4866
+ var modelVariant = _a.modelVariant;
4867
+ return modelVariant === 'CHAT';
4868
+ })
4869
+ .map(function (_a) {
4870
+ var modelName = _a.modelName;
4871
+ return modelName;
4872
+ })
4873
+ .join(',');
4874
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
4875
+ case 3:
4876
+ result = _d.sent();
4877
+ assertsExecutionSuccessful(result);
4878
+ outputParameters = result.outputParameters;
4879
+ modelRequirementsRaw = outputParameters.modelRequirements;
4880
+ modelRequirements = JSON.parse(modelRequirementsRaw);
4881
+ if (isVerbose) {
4882
+ console.info("PERSONA ".concat(personaDescription), modelRequirements);
4883
+ }
4884
+ modelName = modelRequirements.modelName, systemMessage = modelRequirements.systemMessage, temperature = modelRequirements.temperature;
4885
+ return [2 /*return*/, {
4886
+ modelVariant: 'CHAT',
4887
+ modelName: modelName,
4888
+ systemMessage: systemMessage,
4889
+ temperature: temperature,
4890
+ }];
4891
+ }
4892
+ });
4893
+ });
4894
+ }
4895
+ /**
4896
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4897
+ * TODO: [🏢] !! Check validity of `modelName` in pipeline
4898
+ * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4899
+ * TODO: [🏢] !! Check validity of `temperature` in pipeline
4900
+ */
4901
+
4902
+ /**
4903
+ * This error indicates that the promptbook can not retrieve knowledge from external sources
4904
+ *
4905
+ * @public exported from `@promptbook/core`
4906
+ */
4907
+ var KnowledgeScrapeError = /** @class */ (function (_super) {
4908
+ __extends(KnowledgeScrapeError, _super);
4909
+ function KnowledgeScrapeError(message) {
4910
+ var _this = _super.call(this, message) || this;
4911
+ _this.name = 'KnowledgeScrapeError';
4912
+ Object.setPrototypeOf(_this, KnowledgeScrapeError.prototype);
4913
+ return _this;
4914
+ }
4915
+ return KnowledgeScrapeError;
4916
+ }(Error));
4917
+
4918
+ /**
4919
+ * @@@
4920
+ *
4921
+ * Note: `$` is used to indicate that this function is not a pure function - it access global scope
4922
+ *
4923
+ * @private internal function of `$Register`
4924
+ */
4925
+ function $getGlobalScope() {
4926
+ return Function('return this')();
4927
+ }
4928
+
4929
+ /**
4930
+ * @@@
4931
+ *
4932
+ * @param text @@@
4933
+ * @returns @@@
4934
+ * @example 'HELLO_WORLD'
4935
+ * @example 'I_LOVE_PROMPTBOOK'
4936
+ * @public exported from `@promptbook/utils`
4937
+ */
4938
+ function normalizeTo_SCREAMING_CASE(text) {
4939
+ var e_1, _a;
4940
+ var charType;
4941
+ var lastCharType = 'OTHER';
4942
+ var normalizedName = '';
4943
+ try {
4944
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
4945
+ var char = text_1_1.value;
4946
+ var normalizedChar = void 0;
4947
+ if (/^[a-z]$/.test(char)) {
4948
+ charType = 'LOWERCASE';
4949
+ normalizedChar = char.toUpperCase();
4950
+ }
4951
+ else if (/^[A-Z]$/.test(char)) {
4952
+ charType = 'UPPERCASE';
4953
+ normalizedChar = char;
4954
+ }
4955
+ else if (/^[0-9]$/.test(char)) {
4956
+ charType = 'NUMBER';
4957
+ normalizedChar = char;
4958
+ }
4959
+ else {
4960
+ charType = 'OTHER';
4961
+ normalizedChar = '_';
4962
+ }
4963
+ if (charType !== lastCharType &&
4964
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
4965
+ !(lastCharType === 'NUMBER') &&
4966
+ !(charType === 'NUMBER')) {
4967
+ normalizedName += '_';
4968
+ }
4969
+ normalizedName += normalizedChar;
4970
+ lastCharType = charType;
4971
+ }
4972
+ }
4973
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4974
+ finally {
4975
+ try {
4976
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
4977
+ }
4978
+ finally { if (e_1) throw e_1.error; }
4979
+ }
4980
+ normalizedName = normalizedName.replace(/_+/g, '_');
4981
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
4982
+ normalizedName = normalizedName.replace(/^_/, '');
4983
+ normalizedName = normalizedName.replace(/_$/, '');
4984
+ return normalizedName;
4985
+ }
4986
+ /**
4987
+ * TODO: Tests
4988
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
4989
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
4990
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
4991
+ * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
4992
+ * TODO: [🌺] Use some intermediate util splitWords
4993
+ */
4994
+
4995
+ /**
4996
+ * @@@
4997
+ *
4998
+ * @param text @@@
4999
+ * @returns @@@
5000
+ * @example 'hello_world'
5001
+ * @example 'i_love_promptbook'
5002
+ * @public exported from `@promptbook/utils`
5003
+ */
5004
+ function normalizeTo_snake_case(text) {
5005
+ return normalizeTo_SCREAMING_CASE(text).toLowerCase();
5006
+ }
5007
+
5008
+ /**
5009
+ * Register is @@@
5010
+ *
5011
+ * Note: `$` is used to indicate that this function is not a pure function - it accesses and adds variables in global scope.
5012
+ *
5013
+ * @private internal utility, exported are only signleton instances of this class
5014
+ */
5015
+ var $Register = /** @class */ (function () {
5016
+ function $Register(registerName) {
5017
+ this.registerName = registerName;
5018
+ var storageName = "_promptbook_".concat(normalizeTo_snake_case(registerName));
5019
+ var globalScope = $getGlobalScope();
5020
+ if (globalScope[storageName] === undefined) {
5021
+ globalScope[storageName] = [];
5022
+ }
5023
+ else if (!Array.isArray(globalScope[storageName])) {
5024
+ throw new UnexpectedError("Expected (global) ".concat(storageName, " to be an array, but got ").concat(typeof globalScope[storageName]));
5025
+ }
5026
+ this.storage = globalScope[storageName];
5027
+ }
5028
+ $Register.prototype.list = function () {
5029
+ // <- TODO: ReadonlyDeep<Array<TRegistered>>
5030
+ return this.storage;
5031
+ };
5032
+ $Register.prototype.register = function (registered) {
5033
+ var packageName = registered.packageName, className = registered.className;
5034
+ var existingRegistrationIndex = this.storage.findIndex(function (item) { return item.packageName === packageName && item.className === className; });
5035
+ var existingRegistration = this.storage[existingRegistrationIndex];
5036
+ if (!existingRegistration) {
5037
+ this.storage.push(registered);
5038
+ }
5039
+ else {
5040
+ this.storage[existingRegistrationIndex] = registered;
5041
+ }
5042
+ return {
5043
+ registerName: this.registerName,
5044
+ packageName: packageName,
5045
+ className: className,
5046
+ get isDestroyed() {
5047
+ return false;
5048
+ },
5049
+ destroy: function () {
5050
+ throw new NotYetImplementedError("Registration to ".concat(this.registerName, " is permanent in this version of Promptbook"));
5051
+ },
5052
+ };
5053
+ };
5054
+ return $Register;
5055
+ }());
5056
+
5057
+ /**
5058
+ * @@@
5059
+ *
5060
+ * Note: `$` is used to indicate that this interacts with the global scope
5061
+ * @singleton Only one instance of each register is created per build, but thare can be more @@@
5062
+ * @public exported from `@promptbook/core`
5063
+ */
5064
+ var $scrapersMetadataRegister = new $Register('scrapers_metadata');
5065
+ /**
5066
+ * TODO: [®] DRY Register logic
5067
+ */
5068
+
5069
+ /**
5070
+ * @@@
5071
+ *
5072
+ * Note: `$` is used to indicate that this interacts with the global scope
5073
+ * @singleton Only one instance of each register is created per build, but thare can be more @@@
5074
+ * @public exported from `@promptbook/core`
5075
+ */
5076
+ var $scrapersRegister = new $Register('scraper_constructors');
5077
+ /**
5078
+ * TODO: [®] DRY Register logic
5079
+ */
5080
+
5081
+ // TODO: !!!!!! Maybe delete this function
5082
+ /**
5083
+ * Creates a message with all registered scrapers
5084
+ *
5085
+ * Note: This function is used to create a (error) message when there is no scraper for particular mime type
5086
+ *
5087
+ * @private internal function of `createScrapersFromConfiguration` and `createScrapersFromEnv`
5088
+ */
5089
+ function $registeredScrapersMessage() {
5090
+ var e_1, _a, e_2, _b;
5091
+ /**
5092
+ * Mixes registered scrapers from $scrapersMetadataRegister and $scrapersRegister
5093
+ */
5094
+ var all = [];
5095
+ var _loop_1 = function (packageName, className) {
5096
+ if (all.some(function (item) { return item.packageName === packageName && item.className === className; })) {
5097
+ return "continue";
5098
+ }
5099
+ all.push({ packageName: packageName, className: className });
5100
+ };
5101
+ try {
5102
+ for (var _c = __values($scrapersMetadataRegister.list()), _d = _c.next(); !_d.done; _d = _c.next()) {
5103
+ var _e = _d.value, packageName = _e.packageName, className = _e.className;
5104
+ _loop_1(packageName, className);
5105
+ }
5106
+ }
5107
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5108
+ finally {
5109
+ try {
5110
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
5111
+ }
5112
+ finally { if (e_1) throw e_1.error; }
5113
+ }
5114
+ var _loop_2 = function (packageName, className) {
5115
+ if (all.some(function (item) { return item.packageName === packageName && item.className === className; })) {
5116
+ return "continue";
5117
+ }
5118
+ all.push({ packageName: packageName, className: className });
5119
+ };
5120
+ try {
5121
+ for (var _f = __values($scrapersRegister.list()), _g = _f.next(); !_g.done; _g = _f.next()) {
5122
+ var _h = _g.value, packageName = _h.packageName, className = _h.className;
5123
+ _loop_2(packageName, className);
5124
+ }
5125
+ }
5126
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5127
+ finally {
5128
+ try {
5129
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
5130
+ }
5131
+ finally { if (e_2) throw e_2.error; }
5132
+ }
5133
+ var metadata = all.map(function (metadata) {
5134
+ var isMetadataAviailable = $scrapersMetadataRegister
5135
+ .list()
5136
+ .find(function (_a) {
5137
+ var packageName = _a.packageName, className = _a.className;
5138
+ return metadata.packageName === packageName && metadata.className === className;
5139
+ });
5140
+ var isInstalled = $scrapersRegister
5141
+ .list()
5142
+ .find(function (_a) {
5143
+ var packageName = _a.packageName, className = _a.className;
5144
+ return metadata.packageName === packageName && metadata.className === className;
5145
+ });
5146
+ return __assign(__assign({}, metadata), { isMetadataAviailable: isMetadataAviailable, isInstalled: isInstalled });
5147
+ });
5148
+ if (metadata.length === 0) {
5149
+ return "No scrapers are available";
5150
+ }
5151
+ return spaceTrim(function (block) { return "\n Available scrapers are:\n ".concat(block(metadata
5152
+ .map(function (_a, i) {
5153
+ var packageName = _a.packageName, className = _a.className, isMetadataAviailable = _a.isMetadataAviailable, isInstalled = _a.isInstalled;
5154
+ var more;
5155
+ if (just(false)) {
5156
+ more = '';
5157
+ }
5158
+ else if (!isMetadataAviailable && !isInstalled) {
5159
+ // TODO: [�][�] Maybe do allow to do auto-install if package not registered and not found
5160
+ more = "(not installed and no metadata, looks like a unexpected behavior)";
5161
+ }
5162
+ else if (isMetadataAviailable && !isInstalled) {
5163
+ // TODO: [�][�]
5164
+ more = "(not installed)";
5165
+ }
5166
+ else if (!isMetadataAviailable && isInstalled) {
5167
+ more = "(no metadata, looks like a unexpected behavior)";
5168
+ }
5169
+ else if (isMetadataAviailable && isInstalled) {
5170
+ more = "(installed)";
5171
+ }
5172
+ else {
5173
+ more = "(unknown state, looks like a unexpected behavior)";
5174
+ }
5175
+ return "".concat(i + 1, ") `").concat(className, "` from `").concat(packageName, "` ").concat(more);
5176
+ })
5177
+ .join('\n')), "\n "); });
5178
+ }
5179
+ /**
5180
+ * TODO: [®] DRY Register logic
5181
+ */
4709
5182
 
4710
5183
  /**
4711
- * Creates executor function from pipeline and execution tools.
5184
+ * @@@
4712
5185
  *
4713
- * @returns The executor function
4714
- * @throws {PipelineLogicError} on logical error in the pipeline
4715
- * @public exported from `@promptbook/core`
5186
+ * @param text @@@
5187
+ * @returns @@@
5188
+ * @example 'hello-world'
5189
+ * @example 'i-love-promptbook'
5190
+ * @public exported from `@promptbook/utils`
4716
5191
  */
4717
- function createPipelineExecutor(options) {
4718
- var _this = this;
4719
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4720
- 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;
4721
- validatePipeline(pipeline);
4722
- var pipelineIdentification = (function () {
4723
- // Note: This is a 😐 implementation of [🚞]
4724
- var _ = [];
4725
- if (pipeline.sourceFile !== undefined) {
4726
- _.push("File: ".concat(pipeline.sourceFile));
4727
- }
4728
- if (pipeline.pipelineUrl !== undefined) {
4729
- _.push("Url: ".concat(pipeline.pipelineUrl));
5192
+ function normalizeToKebabCase(text) {
5193
+ var e_1, _a;
5194
+ text = removeDiacritics(text);
5195
+ var charType;
5196
+ var lastCharType = 'OTHER';
5197
+ var normalizedName = '';
5198
+ try {
5199
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5200
+ var char = text_1_1.value;
5201
+ var normalizedChar = void 0;
5202
+ if (/^[a-z]$/.test(char)) {
5203
+ charType = 'LOWERCASE';
5204
+ normalizedChar = char;
5205
+ }
5206
+ else if (/^[A-Z]$/.test(char)) {
5207
+ charType = 'UPPERCASE';
5208
+ normalizedChar = char.toLowerCase();
5209
+ }
5210
+ else if (/^[0-9]$/.test(char)) {
5211
+ charType = 'NUMBER';
5212
+ normalizedChar = char;
5213
+ }
5214
+ else {
5215
+ charType = 'OTHER';
5216
+ normalizedChar = '-';
5217
+ }
5218
+ if (charType !== lastCharType &&
5219
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
5220
+ !(lastCharType === 'NUMBER') &&
5221
+ !(charType === 'NUMBER')) {
5222
+ normalizedName += '-';
5223
+ }
5224
+ normalizedName += normalizedChar;
5225
+ lastCharType = charType;
4730
5226
  }
4731
- return _.join('\n');
4732
- })();
4733
- var preparedPipeline;
4734
- if (isPipelinePrepared(pipeline)) {
4735
- preparedPipeline = pipeline;
4736
5227
  }
4737
- else if (isNotPreparedWarningSupressed !== true) {
4738
- console.warn(spaceTrim$1(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
5228
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5229
+ finally {
5230
+ try {
5231
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5232
+ }
5233
+ finally { if (e_1) throw e_1.error; }
4739
5234
  }
4740
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
5235
+ normalizedName = normalizedName.split(/-+/g).join('-');
5236
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
5237
+ normalizedName = normalizedName.replace(/^-/, '');
5238
+ normalizedName = normalizedName.replace(/-$/, '');
5239
+ return normalizedName;
5240
+ }
5241
+
5242
+ /**
5243
+ * Creates unique name for the source
5244
+ *
5245
+ * @private within the repository
5246
+ */
5247
+ function sourceContentToName(sourceContent) {
5248
+ // TODO: !!!!!! Better name for source than gibberish hash
5249
+ var hash = SHA256(hexEncoder.parse(JSON.stringify(sourceContent)))
5250
+ // <- TODO: [🥬] Encapsulate sha256 to some private utility function
5251
+ .toString( /* hex */)
5252
+ .substring(0, 20);
5253
+ // <- TODO: [🥬] Make some system for hashes and ids of promptbook
5254
+ var semanticName = normalizeToKebabCase(sourceContent.substring(0, 20));
5255
+ var pieces = ['source', semanticName, hash].filter(function (piece) { return piece !== ''; });
5256
+ var name = pieces.join('-').split('--').join('-');
5257
+ // <- TODO: Use MAX_FILENAME_LENGTH
5258
+ return name;
5259
+ }
5260
+ /**
5261
+ * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
5262
+ */
5263
+
5264
+ /**
5265
+ * Detects if the code is running in a Node.js environment
5266
+ *
5267
+ * Note: `$` is used to indicate that this function is not a pure function - it looks at the global object to determine the environment
5268
+ *
5269
+ * @public exported from `@promptbook/utils`
5270
+ */
5271
+ var $isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
5272
+
5273
+ /**
5274
+ * Checks if the file exists
5275
+ *
5276
+ * Note: `$` is used to indicate that this function is not a pure function - it looks at the filesystem
5277
+ *
5278
+ * @private within the repository
5279
+ */
5280
+ function $isFileExisting(filename) {
5281
+ return __awaiter(this, void 0, void 0, function () {
5282
+ var isReadAccessAllowed, isFile;
4741
5283
  return __generator(this, function (_a) {
4742
- return [2 /*return*/, executePipeline({
4743
- pipeline: pipeline,
4744
- preparedPipeline: preparedPipeline,
4745
- setPreparedPipeline: function (newPreparedPipeline) {
4746
- preparedPipeline = newPreparedPipeline;
4747
- },
4748
- inputParameters: inputParameters,
4749
- tools: tools,
4750
- onProgress: onProgress,
4751
- pipelineIdentification: pipelineIdentification,
4752
- settings: {
4753
- maxExecutionAttempts: maxExecutionAttempts,
4754
- maxParallelCount: maxParallelCount,
4755
- csvSettings: csvSettings,
4756
- isVerbose: isVerbose,
4757
- isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4758
- },
4759
- })];
5284
+ switch (_a.label) {
5285
+ case 0:
5286
+ if (!$isRunningInNode()) {
5287
+ throw new EnvironmentMismatchError('Function `$isFileExisting` works only in Node environment.js');
5288
+ }
5289
+ return [4 /*yield*/, access(filename, constants.R_OK)
5290
+ .then(function () { return true; })
5291
+ .catch(function () { return false; })];
5292
+ case 1:
5293
+ isReadAccessAllowed = _a.sent();
5294
+ if (!isReadAccessAllowed) {
5295
+ return [2 /*return*/, false];
5296
+ }
5297
+ return [4 /*yield*/, stat(filename)
5298
+ .then(function (fileStat) { return fileStat.isFile(); })
5299
+ .catch(function () { return false; })];
5300
+ case 2:
5301
+ isFile = _a.sent();
5302
+ return [2 /*return*/, isFile];
5303
+ }
4760
5304
  });
4761
- }); };
4762
- return pipelineExecutor;
5305
+ });
5306
+ }
5307
+ /**
5308
+ * Note: [🟢 !!!!!! After fix makeKnowledgeSourceHandler] Code in this file should never be published outside of `@promptbook/node` and `@promptbook/cli`
5309
+ * TODO: [🐠] This can be a validator - with variants that return true/false and variants that throw errors with meaningless messages
5310
+ * TODO: [🖇] What about symlinks?
5311
+ */
5312
+
5313
+ /**
5314
+ * Convert file extension to mime type
5315
+ *
5316
+ * @private within the repository
5317
+ */
5318
+ function extensionToMimeType(value) {
5319
+ return lookup(value) || 'application/octet-stream';
5320
+ }
5321
+
5322
+ /**
5323
+ * Get the file extension from a file name
5324
+ *
5325
+ * @private within the repository
5326
+ */
5327
+ function getFileExtension(value) {
5328
+ var match = value.match(/\.([0-9a-z]+)(?:[?#]|$)/i);
5329
+ return match ? match[1].toLowerCase() : null;
5330
+ }
5331
+
5332
+ /**
5333
+ * Tests if given string is valid URL.
5334
+ *
5335
+ * Note: This does not check if the file exists only if the path is valid
5336
+ * @public exported from `@promptbook/utils`
5337
+ */
5338
+ function isValidFilePath(filename) {
5339
+ if (typeof filename !== 'string') {
5340
+ return false;
5341
+ }
5342
+ var filenameSlashes = filename.split('\\').join('/');
5343
+ // Absolute Unix path: /hello.txt
5344
+ if (/^(\/)/i.test(filenameSlashes)) {
5345
+ return true;
5346
+ }
5347
+ // Absolute Windows path: /hello.txt
5348
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
5349
+ return true;
5350
+ }
5351
+ // Relative path: ./hello.txt
5352
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
5353
+ return true;
5354
+ }
5355
+ return false;
4763
5356
  }
4764
5357
 
4765
5358
  /**
4766
5359
  * @@@
4767
5360
  *
4768
- * @public exported from `@promptbook/core`
5361
+ * @private for scraper utilities
4769
5362
  */
4770
- function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?maybe not) Always the file */, options) {
5363
+ function makeKnowledgeSourceHandler(knowledgeSource, options) {
5364
+ var _a;
4771
5365
  return __awaiter(this, void 0, void 0, function () {
4772
- var llmTools, _a, maxParallelCount, _b, isVerbose, collection, prepareKnowledgeFromMarkdownExecutor, _c, prepareTitleExecutor, _d, prepareKeywordsExecutor, _e, result, outputParameters, knowledgePiecesRaw, knowledgeTextPieces, knowledge;
4773
- var _f, _g, _h;
4774
- var _this = this;
4775
- return __generator(this, function (_j) {
4776
- switch (_j.label) {
5366
+ var sourceContent, name, _b, _c, rootDirname, _d,
5367
+ // <- TODO: process.cwd() if running in Node.js
5368
+ isVerbose, url, response_1, mimeType, filename_1, fileExtension, mimeType_1;
5369
+ return __generator(this, function (_e) {
5370
+ switch (_e.label) {
4777
5371
  case 0:
4778
- llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
4779
- TODO_USE(maxParallelCount); // <- [🪂]
4780
- collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
4781
- _c = createPipelineExecutor;
4782
- _f = {};
4783
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
5372
+ sourceContent = knowledgeSource.sourceContent;
5373
+ name = knowledgeSource.name;
5374
+ _b = options || {}, _c = _b.rootDirname, rootDirname = _c === void 0 ? null : _c, _d = _b.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d;
5375
+ TODO_USE(isVerbose);
5376
+ if (!name) {
5377
+ name = sourceContentToName(sourceContent);
5378
+ }
5379
+ if (!isValidUrl(sourceContent)) return [3 /*break*/, 2];
5380
+ url = sourceContent;
5381
+ return [4 /*yield*/, fetch(url)];
4784
5382
  case 1:
4785
- prepareKnowledgeFromMarkdownExecutor = _c.apply(void 0, [(_f.pipeline = _j.sent(),
4786
- _f.tools = {
4787
- llm: llmTools,
5383
+ response_1 = _e.sent();
5384
+ mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5385
+ return [2 /*return*/, {
5386
+ source: name,
5387
+ filename: null,
5388
+ url: url,
5389
+ mimeType: mimeType,
5390
+ asBlob: function () {
5391
+ return __awaiter(this, void 0, void 0, function () {
5392
+ var content;
5393
+ return __generator(this, function (_a) {
5394
+ switch (_a.label) {
5395
+ case 0: return [4 /*yield*/, response_1.blob()];
5396
+ case 1:
5397
+ content = _a.sent();
5398
+ return [2 /*return*/, content];
5399
+ }
5400
+ });
5401
+ });
4788
5402
  },
4789
- _f)]);
4790
- _d = createPipelineExecutor;
4791
- _g = {};
4792
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md')];
4793
- case 2:
4794
- prepareTitleExecutor = _d.apply(void 0, [(_g.pipeline = _j.sent(),
4795
- _g.tools = {
4796
- llm: llmTools,
5403
+ asJson: function () {
5404
+ return __awaiter(this, void 0, void 0, function () {
5405
+ var content;
5406
+ return __generator(this, function (_a) {
5407
+ switch (_a.label) {
5408
+ case 0: return [4 /*yield*/, response_1.json()];
5409
+ case 1:
5410
+ content = _a.sent();
5411
+ return [2 /*return*/, content];
5412
+ }
5413
+ });
5414
+ });
4797
5415
  },
4798
- _g)]);
4799
- _e = createPipelineExecutor;
4800
- _h = {};
4801
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md')];
4802
- case 3:
4803
- prepareKeywordsExecutor = _e.apply(void 0, [(_h.pipeline = _j.sent(),
4804
- _h.tools = {
4805
- llm: llmTools,
5416
+ asText: function () {
5417
+ return __awaiter(this, void 0, void 0, function () {
5418
+ var content;
5419
+ return __generator(this, function (_a) {
5420
+ switch (_a.label) {
5421
+ case 0: return [4 /*yield*/, response_1.text()];
5422
+ case 1:
5423
+ content = _a.sent();
5424
+ return [2 /*return*/, content];
5425
+ }
5426
+ });
5427
+ });
4806
5428
  },
4807
- _h)]);
4808
- return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent })];
4809
- case 4:
4810
- result = _j.sent();
4811
- assertsExecutionSuccessful(result);
4812
- outputParameters = result.outputParameters;
4813
- knowledgePiecesRaw = outputParameters.knowledgePieces;
4814
- knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4815
- // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4816
- if (isVerbose) {
4817
- console.info('knowledgeTextPieces:', knowledgeTextPieces);
5429
+ }];
5430
+ case 2:
5431
+ if (!(isValidFilePath(sourceContent) || /\.[a-z]{1,10}$/i.exec(sourceContent))) return [3 /*break*/, 4];
5432
+ if (!$isRunningInNode()) {
5433
+ throw new EnvironmentMismatchError('Importing knowledge source file works only in Node.js environment');
4818
5434
  }
4819
- return [4 /*yield*/, Promise.all(
4820
- // TODO: [🪂] !! Do not send all at once but in chunks
4821
- knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
4822
- var name, title, knowledgePieceContent, keywords, index, titleResult, _a, titleRaw, keywordsResult, _b, keywordsRaw, embeddingResult, error_1;
4823
- return __generator(this, function (_c) {
4824
- switch (_c.label) {
4825
- case 0:
4826
- name = "piece-".concat(i);
4827
- title = spaceTrim(knowledgeTextPiece.substring(0, 100));
4828
- knowledgePieceContent = spaceTrim(knowledgeTextPiece);
4829
- keywords = [];
4830
- index = [];
4831
- _c.label = 1;
4832
- case 1:
4833
- _c.trys.push([1, 7, , 8]);
4834
- return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent })];
4835
- case 2:
4836
- titleResult = _c.sent();
4837
- _a = titleResult.outputParameters.title, titleRaw = _a === void 0 ? 'Untitled' : _a;
4838
- title = spaceTrim(titleRaw) /* <- TODO: Maybe do in pipeline */;
4839
- name = titleToName(title);
4840
- return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent })];
4841
- case 3:
4842
- keywordsResult = _c.sent();
4843
- _b = keywordsResult.outputParameters.keywords, keywordsRaw = _b === void 0 ? '' : _b;
4844
- keywords = (keywordsRaw || '')
4845
- .split(',')
4846
- .map(function (keyword) { return keyword.trim(); })
4847
- .filter(function (keyword) { return keyword !== ''; });
4848
- if (isVerbose) {
4849
- console.info("Keywords for \"".concat(title, "\":"), keywords);
5435
+ if (rootDirname === null) {
5436
+ throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
5437
+ // <- TODO: [🧠] What is the best error type here`
5438
+ }
5439
+ filename_1 = join(rootDirname, sourceContent).split('\\').join('/');
5440
+ fileExtension = getFileExtension(filename_1);
5441
+ mimeType_1 = extensionToMimeType(fileExtension || '');
5442
+ return [4 /*yield*/, $isFileExisting(filename_1)];
5443
+ case 3:
5444
+ if (!(_e.sent())) {
5445
+ throw new NotFoundError(spaceTrim(function (block) { return "\n Can not make source handler for file which does not exist:\n\n File:\n ".concat(block(filename_1), "\n "); }));
5446
+ }
5447
+ // TODO: !!!!!! Test security file - file is scoped to the project (maybe do this in `filesystemTools`)
5448
+ return [2 /*return*/, {
5449
+ source: name,
5450
+ filename: filename_1,
5451
+ url: null,
5452
+ mimeType: mimeType_1,
5453
+ asBlob: function () {
5454
+ return __awaiter(this, void 0, void 0, function () {
5455
+ var content;
5456
+ return __generator(this, function (_a) {
5457
+ switch (_a.label) {
5458
+ case 0: return [4 /*yield*/, readFile(filename_1)];
5459
+ case 1:
5460
+ content = _a.sent();
5461
+ return [2 /*return*/, new Blob([
5462
+ content,
5463
+ // <- TODO: !!!!!! Maybe not working
5464
+ ], { type: mimeType_1 })];
4850
5465
  }
4851
- if (!!llmTools.callEmbeddingModel) return [3 /*break*/, 4];
4852
- // TODO: [🟥] Detect browser / node and make it colorfull
4853
- console.error('No callEmbeddingModel function provided');
4854
- return [3 /*break*/, 6];
4855
- case 4: return [4 /*yield*/, llmTools.callEmbeddingModel({
4856
- title: "Embedding for ".concat(title) /* <- Note: No impact on embedding result itself, just for logging */,
4857
- parameters: {},
4858
- content: knowledgePieceContent,
4859
- modelRequirements: {
4860
- modelVariant: 'EMBEDDING',
4861
- },
4862
- })];
4863
- case 5:
4864
- embeddingResult = _c.sent();
4865
- index.push({
4866
- modelName: embeddingResult.modelName,
4867
- position: embeddingResult.content,
4868
- });
4869
- _c.label = 6;
4870
- case 6: return [3 /*break*/, 8];
4871
- case 7:
4872
- error_1 = _c.sent();
4873
- // Note: Here is expected error:
4874
- // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4875
- if (!(error_1 instanceof PipelineExecutionError)) {
4876
- throw error_1;
5466
+ });
5467
+ });
5468
+ },
5469
+ asJson: function () {
5470
+ return __awaiter(this, void 0, void 0, function () {
5471
+ var _a, _b;
5472
+ return __generator(this, function (_c) {
5473
+ switch (_c.label) {
5474
+ case 0:
5475
+ _b = (_a = JSON).parse;
5476
+ return [4 /*yield*/, readFile(filename_1, 'utf-8')];
5477
+ case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
4877
5478
  }
4878
- // TODO: [🟥] Detect browser / node and make it colorfull
4879
- console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4880
- return [3 /*break*/, 8];
4881
- case 8: return [2 /*return*/, {
4882
- name: name,
4883
- title: title,
4884
- content: knowledgePieceContent,
4885
- keywords: keywords,
4886
- index: index,
4887
- // <- TODO: [☀] sources,
4888
- }];
4889
- }
4890
- });
4891
- }); }))];
4892
- case 5:
4893
- knowledge = _j.sent();
4894
- return [2 /*return*/, knowledge];
5479
+ });
5480
+ });
5481
+ },
5482
+ asText: function () {
5483
+ return __awaiter(this, void 0, void 0, function () {
5484
+ return __generator(this, function (_a) {
5485
+ switch (_a.label) {
5486
+ case 0: return [4 /*yield*/, readFile(filename_1, 'utf-8')];
5487
+ case 1: return [2 /*return*/, _a.sent()];
5488
+ }
5489
+ });
5490
+ });
5491
+ },
5492
+ }];
5493
+ case 4: return [2 /*return*/, {
5494
+ source: name,
5495
+ filename: null,
5496
+ url: null,
5497
+ mimeType: 'text/markdown',
5498
+ asText: function () {
5499
+ return knowledgeSource.sourceContent;
5500
+ },
5501
+ asJson: function () {
5502
+ throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
5503
+ },
5504
+ asBlob: function () {
5505
+ throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asBlob`');
5506
+ },
5507
+ }];
4895
5508
  }
4896
5509
  });
4897
5510
  });
4898
5511
  }
4899
5512
  /**
4900
- * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4901
- * TODO: [🪂] Do it in parallel 11:11
4902
- * Note: No need to aggregate usage here, it is done by intercepting the llmTools
5513
+ * TODO: !!!!!!! Maybe constrain to @promptbook/node bundle
4903
5514
  */
4904
5515
 
4905
5516
  /**
@@ -4908,23 +5519,64 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4908
5519
  * @see https://github.com/webgptorg/promptbook/discussions/41
4909
5520
  * @public exported from `@promptbook/core`
4910
5521
  */
4911
- function prepareKnowledgePieces(knowledgeSources, options) {
5522
+ function prepareKnowledgePieces(knowledgeSources, tools, options) {
4912
5523
  return __awaiter(this, void 0, void 0, function () {
4913
- var _a, maxParallelCount, knowledgePrepared;
5524
+ var _a, maxParallelCount, rootDirname, _b, isVerbose, knowledgePreparedUnflatten, knowledgePrepared;
4914
5525
  var _this = this;
4915
- return __generator(this, function (_b) {
4916
- switch (_b.label) {
5526
+ return __generator(this, function (_c) {
5527
+ switch (_c.label) {
4917
5528
  case 0:
4918
- _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4919
- knowledgePrepared = [];
4920
- return [4 /*yield*/, forEachAsync(knowledgeSources, { maxParallelCount: maxParallelCount }, function (knowledgeSource) { return __awaiter(_this, void 0, void 0, function () {
4921
- var partialPieces, pieces;
4922
- return __generator(this, function (_a) {
4923
- switch (_a.label) {
4924
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4925
- options)];
5529
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, rootDirname = options.rootDirname, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
5530
+ knowledgePreparedUnflatten = new Array(knowledgeSources.length);
5531
+ return [4 /*yield*/, forEachAsync(knowledgeSources, { maxParallelCount: maxParallelCount }, function (knowledgeSource, index) { return __awaiter(_this, void 0, void 0, function () {
5532
+ var partialPieces, sourceHandler, _a, _b, scraper, partialPiecesUnchecked, e_1_1, pieces;
5533
+ var e_1, _c;
5534
+ return __generator(this, function (_d) {
5535
+ switch (_d.label) {
5536
+ case 0:
5537
+ partialPieces = null;
5538
+ return [4 /*yield*/, makeKnowledgeSourceHandler(knowledgeSource, { rootDirname: rootDirname, isVerbose: isVerbose })];
4926
5539
  case 1:
4927
- partialPieces = _a.sent();
5540
+ sourceHandler = _d.sent();
5541
+ _d.label = 2;
5542
+ case 2:
5543
+ _d.trys.push([2, 7, 8, 9]);
5544
+ _a = __values(arrayableToArray(tools.scrapers)), _b = _a.next();
5545
+ _d.label = 3;
5546
+ case 3:
5547
+ if (!!_b.done) return [3 /*break*/, 6];
5548
+ scraper = _b.value;
5549
+ if (!scraper.metadata.mimeTypes.includes(sourceHandler.mimeType)
5550
+ // <- TODO: [🦔] Implement mime-type wildcards
5551
+ ) {
5552
+ return [3 /*break*/, 5];
5553
+ }
5554
+ return [4 /*yield*/, scraper.scrape(sourceHandler)];
5555
+ case 4:
5556
+ partialPiecesUnchecked = _d.sent();
5557
+ if (partialPiecesUnchecked !== null) {
5558
+ partialPieces = partialPiecesUnchecked;
5559
+ return [3 /*break*/, 6];
5560
+ }
5561
+ _d.label = 5;
5562
+ case 5:
5563
+ _b = _a.next();
5564
+ return [3 /*break*/, 3];
5565
+ case 6: return [3 /*break*/, 9];
5566
+ case 7:
5567
+ e_1_1 = _d.sent();
5568
+ e_1 = { error: e_1_1 };
5569
+ return [3 /*break*/, 9];
5570
+ case 8:
5571
+ try {
5572
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
5573
+ }
5574
+ finally { if (e_1) throw e_1.error; }
5575
+ return [7 /*endfinally*/];
5576
+ case 9:
5577
+ if (partialPieces === null) {
5578
+ throw new KnowledgeScrapeError(spaceTrim(function (block) { return "\n Cannot scrape knowledge from source: ".concat(knowledgeSource.sourceContent, "\n\n No scraper found for the mime type \"").concat(sourceHandler.mimeType, "\"\n\n ").concat(block($registeredScrapersMessage()), "\n\n\n "); }));
5579
+ }
4928
5580
  pieces = partialPieces.map(function (partialPiece) { return (__assign(__assign({}, partialPiece), { sources: [
4929
5581
  {
4930
5582
  name: knowledgeSource.name,
@@ -4932,13 +5584,14 @@ function prepareKnowledgePieces(knowledgeSources, options) {
4932
5584
  // <- TODO: [❎]
4933
5585
  },
4934
5586
  ] })); });
4935
- knowledgePrepared.push.apply(knowledgePrepared, __spreadArray([], __read(pieces), false));
5587
+ knowledgePreparedUnflatten[index] = pieces;
4936
5588
  return [2 /*return*/];
4937
5589
  }
4938
5590
  });
4939
5591
  }); })];
4940
5592
  case 1:
4941
- _b.sent();
5593
+ _c.sent();
5594
+ knowledgePrepared = knowledgePreparedUnflatten.flat();
4942
5595
  return [2 /*return*/, knowledgePrepared];
4943
5596
  }
4944
5597
  });
@@ -4955,7 +5608,7 @@ TODO: [🧊] This is how it can look in future
4955
5608
  >
4956
5609
  > export async function prepareKnowledgePieces(
4957
5610
  > knowledge: PrepareKnowledgeKnowledge,
4958
- > options: PrepareOptions,
5611
+ > options: PrepareAndScrapeOptions,
4959
5612
  > ):
4960
5613
  */
4961
5614
  /**
@@ -4967,158 +5620,6 @@ TODO: [🧊] This is how it can look in future
4967
5620
  * [ ] One piece can have multiple sources
4968
5621
  */
4969
5622
 
4970
- /**
4971
- * Intercepts LLM tools and counts total usage of the tools
4972
- *
4973
- * @param llmTools LLM tools to be intercepted with usage counting
4974
- * @returns LLM tools with same functionality with added total cost counting
4975
- * @public exported from `@promptbook/core`
4976
- */
4977
- function countTotalUsage(llmTools) {
4978
- var _this = this;
4979
- var totalUsage = ZERO_USAGE;
4980
- var proxyTools = {
4981
- get title() {
4982
- // TODO: [🧠] Maybe put here some suffix
4983
- return llmTools.title;
4984
- },
4985
- get description() {
4986
- // TODO: [🧠] Maybe put here some suffix
4987
- return llmTools.description;
4988
- },
4989
- checkConfiguration: function () {
4990
- return __awaiter(this, void 0, void 0, function () {
4991
- return __generator(this, function (_a) {
4992
- return [2 /*return*/, /* not await */ llmTools.checkConfiguration()];
4993
- });
4994
- });
4995
- },
4996
- listModels: function () {
4997
- return /* not await */ llmTools.listModels();
4998
- },
4999
- getTotalUsage: function () {
5000
- // <- Note: [🥫] Not using getter `get totalUsage` but `getTotalUsage` to allow this object to be proxied
5001
- return totalUsage;
5002
- },
5003
- };
5004
- if (llmTools.callChatModel !== undefined) {
5005
- proxyTools.callChatModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
5006
- var promptResult;
5007
- return __generator(this, function (_a) {
5008
- switch (_a.label) {
5009
- case 0: return [4 /*yield*/, llmTools.callChatModel(prompt)];
5010
- case 1:
5011
- promptResult = _a.sent();
5012
- totalUsage = addUsage(totalUsage, promptResult.usage);
5013
- return [2 /*return*/, promptResult];
5014
- }
5015
- });
5016
- }); };
5017
- }
5018
- if (llmTools.callCompletionModel !== undefined) {
5019
- proxyTools.callCompletionModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
5020
- var promptResult;
5021
- return __generator(this, function (_a) {
5022
- switch (_a.label) {
5023
- case 0: return [4 /*yield*/, llmTools.callCompletionModel(prompt)];
5024
- case 1:
5025
- promptResult = _a.sent();
5026
- totalUsage = addUsage(totalUsage, promptResult.usage);
5027
- return [2 /*return*/, promptResult];
5028
- }
5029
- });
5030
- }); };
5031
- }
5032
- if (llmTools.callEmbeddingModel !== undefined) {
5033
- proxyTools.callEmbeddingModel = function (prompt) { return __awaiter(_this, void 0, void 0, function () {
5034
- var promptResult;
5035
- return __generator(this, function (_a) {
5036
- switch (_a.label) {
5037
- case 0: return [4 /*yield*/, llmTools.callEmbeddingModel(prompt)];
5038
- case 1:
5039
- promptResult = _a.sent();
5040
- totalUsage = addUsage(totalUsage, promptResult.usage);
5041
- return [2 /*return*/, promptResult];
5042
- }
5043
- });
5044
- }); };
5045
- }
5046
- // <- Note: [🤖]
5047
- return proxyTools;
5048
- }
5049
- /**
5050
- * TODO: [🧠][💸] Maybe make some common abstraction `interceptLlmTools` and use here (or use javascript Proxy?)
5051
- * TODO: [🧠] Is there some meaningfull way how to test this util
5052
- * TODO: [🧠][🌯] Maybe a way how to hide ability to `get totalUsage`
5053
- * > const [llmToolsWithUsage,getUsage] = countTotalUsage(llmTools);
5054
- * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
5055
- */
5056
-
5057
- /**
5058
- * Prepares the persona for the pipeline
5059
- *
5060
- * @see https://github.com/webgptorg/promptbook/discussions/22
5061
- * @public exported from `@promptbook/core`
5062
- */
5063
- function preparePersona(personaDescription, options) {
5064
- return __awaiter(this, void 0, void 0, function () {
5065
- var llmTools, _a, isVerbose, collection, preparePersonaExecutor, _b, availableModels, availableModelNames, result, outputParameters, modelRequirementsRaw, modelRequirements, modelName, systemMessage, temperature;
5066
- var _c;
5067
- return __generator(this, function (_d) {
5068
- switch (_d.label) {
5069
- case 0:
5070
- llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? IS_VERBOSE : _a;
5071
- collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
5072
- _b = createPipelineExecutor;
5073
- _c = {};
5074
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-persona.ptbk.md')];
5075
- case 1:
5076
- preparePersonaExecutor = _b.apply(void 0, [(_c.pipeline = _d.sent(),
5077
- _c.tools = {
5078
- llm: llmTools,
5079
- },
5080
- _c)]);
5081
- return [4 /*yield*/, llmTools.listModels()];
5082
- case 2:
5083
- availableModels = _d.sent();
5084
- availableModelNames = availableModels
5085
- .filter(function (_a) {
5086
- var modelVariant = _a.modelVariant;
5087
- return modelVariant === 'CHAT';
5088
- })
5089
- .map(function (_a) {
5090
- var modelName = _a.modelName;
5091
- return modelName;
5092
- })
5093
- .join(',');
5094
- return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
5095
- case 3:
5096
- result = _d.sent();
5097
- assertsExecutionSuccessful(result);
5098
- outputParameters = result.outputParameters;
5099
- modelRequirementsRaw = outputParameters.modelRequirements;
5100
- modelRequirements = JSON.parse(modelRequirementsRaw);
5101
- if (isVerbose) {
5102
- console.info("PERSONA ".concat(personaDescription), modelRequirements);
5103
- }
5104
- modelName = modelRequirements.modelName, systemMessage = modelRequirements.systemMessage, temperature = modelRequirements.temperature;
5105
- return [2 /*return*/, {
5106
- modelVariant: 'CHAT',
5107
- modelName: modelName,
5108
- systemMessage: systemMessage,
5109
- temperature: temperature,
5110
- }];
5111
- }
5112
- });
5113
- });
5114
- }
5115
- /**
5116
- * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
5117
- * TODO: [🏢] !! Check validity of `modelName` in pipeline
5118
- * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
5119
- * TODO: [🏢] !! Check validity of `temperature` in pipeline
5120
- */
5121
-
5122
5623
  /**
5123
5624
  * @@@
5124
5625
  *
@@ -5153,7 +5654,7 @@ function clonePipeline(pipeline) {
5153
5654
  *
5154
5655
  * @public exported from `@promptbook/core`
5155
5656
  */
5156
- function prepareTemplates(pipeline, options) {
5657
+ function prepareTemplates(pipeline, tools, options) {
5157
5658
  return __awaiter(this, void 0, void 0, function () {
5158
5659
  var _a, maxParallelCount, templates, parameters, knowledgePiecesCount, templatesPrepared;
5159
5660
  var _this = this;
@@ -5162,11 +5663,9 @@ function prepareTemplates(pipeline, options) {
5162
5663
  case 0:
5163
5664
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
5164
5665
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
5165
- // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
5666
+ // TODO: [main] !!!!! Apply samples to each template (if missing and is for the template defined)
5166
5667
  TODO_USE(parameters);
5167
- templatesPrepared = new Array(
5168
- // <- TODO: [🧱] Implement in a functional (not new Class) way
5169
- templates.length);
5668
+ templatesPrepared = new Array(templates.length);
5170
5669
  return [4 /*yield*/, forEachAsync(templates, { maxParallelCount: maxParallelCount /* <- TODO: [🪂] When there are subtasks, this maximul limit can be broken */ }, function (template, index) { return __awaiter(_this, void 0, void 0, function () {
5171
5670
  var dependentParameterNames, preparedContent, preparedTemplate;
5172
5671
  return __generator(this, function (_a) {
@@ -5209,14 +5708,14 @@ function prepareTemplates(pipeline, options) {
5209
5708
  * Note: When the pipeline is already prepared, it returns the same pipeline
5210
5709
  * @public exported from `@promptbook/core`
5211
5710
  */
5212
- function preparePipeline(pipeline, options) {
5711
+ function preparePipeline(pipeline, tools, options) {
5213
5712
  return __awaiter(this, void 0, void 0, function () {
5214
- var llmTools, _a, maxParallelCount, _b, isVerbose, parameters, templates,
5713
+ var rootDirname, _a, maxParallelCount, _b, isVerbose, parameters, templates,
5215
5714
  /*
5216
5715
  <- TODO: [🧠][🪑] `promptbookVersion` */
5217
5716
  knowledgeSources /*
5218
5717
  <- TODO: [🧊] `knowledgePieces` */, personas /*
5219
- <- TODO: [🧊] `preparations` */, llmToolsWithUsage, currentPreparation, preparations, preparedPersonas, knowledgeSourcesPrepared, partialknowledgePiecesPrepared, knowledgePiecesPrepared, templatesPrepared /* TODO: parameters: parametersPrepared*/;
5718
+ <- TODO: [🧊] `preparations` */, _llms, llmTools, llmToolsWithUsage, currentPreparation, preparations, preparedPersonas, knowledgeSourcesPrepared, partialknowledgePiecesPrepared, knowledgePiecesPrepared, templatesPrepared /* TODO: parameters: parametersPrepared*/;
5220
5719
  var _this = this;
5221
5720
  return __generator(this, function (_c) {
5222
5721
  switch (_c.label) {
@@ -5224,8 +5723,13 @@ function preparePipeline(pipeline, options) {
5224
5723
  if (isPipelinePrepared(pipeline)) {
5225
5724
  return [2 /*return*/, pipeline];
5226
5725
  }
5227
- llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
5726
+ rootDirname = options.rootDirname, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? IS_VERBOSE : _b;
5228
5727
  parameters = pipeline.parameters, templates = pipeline.templates, knowledgeSources = pipeline.knowledgeSources, personas = pipeline.personas;
5728
+ if (tools === undefined || tools.llm === undefined) {
5729
+ throw new MissingToolsError('LLM tools are required for preparing the pipeline');
5730
+ }
5731
+ _llms = arrayableToArray(tools.llm);
5732
+ llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(_llms), false));
5229
5733
  llmToolsWithUsage = countTotalUsage(llmTools);
5230
5734
  currentPreparation = {
5231
5735
  id: 1,
@@ -5238,15 +5742,13 @@ function preparePipeline(pipeline, options) {
5238
5742
  // <- TODO: [🧊]
5239
5743
  currentPreparation,
5240
5744
  ];
5241
- preparedPersonas = new Array(
5242
- // <- TODO: [🧱] Implement in a functional (not new Class) way
5243
- personas.length);
5745
+ preparedPersonas = new Array(personas.length);
5244
5746
  return [4 /*yield*/, forEachAsync(personas, { maxParallelCount: maxParallelCount /* <- TODO: [🪂] When there are subtasks, this maximul limit can be broken */ }, function (persona, index) { return __awaiter(_this, void 0, void 0, function () {
5245
5747
  var modelRequirements, preparedPersona;
5246
5748
  return __generator(this, function (_a) {
5247
5749
  switch (_a.label) {
5248
- case 0: return [4 /*yield*/, preparePersona(persona.description, {
5249
- llmTools: llmToolsWithUsage,
5750
+ case 0: return [4 /*yield*/, preparePersona(persona.description, __assign(__assign({}, tools), { llm: llmToolsWithUsage }), {
5751
+ rootDirname: rootDirname,
5250
5752
  maxParallelCount: maxParallelCount /* <- TODO: [🪂] */,
5251
5753
  isVerbose: isVerbose,
5252
5754
  })];
@@ -5261,11 +5763,7 @@ function preparePipeline(pipeline, options) {
5261
5763
  case 1:
5262
5764
  _c.sent();
5263
5765
  knowledgeSourcesPrepared = knowledgeSources.map(function (source) { return (__assign(__assign({}, source), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
5264
- return [4 /*yield*/, prepareKnowledgePieces(knowledgeSources /* <- TODO: [🧊] {knowledgeSources, knowledgePieces} */, {
5265
- llmTools: llmToolsWithUsage,
5266
- maxParallelCount: maxParallelCount /* <- TODO: [🪂] */,
5267
- isVerbose: isVerbose,
5268
- })];
5766
+ return [4 /*yield*/, prepareKnowledgePieces(knowledgeSources /* <- TODO: [🧊] {knowledgeSources, knowledgePieces} */, __assign(__assign({}, tools), { llm: llmToolsWithUsage }), __assign(__assign({}, options), { rootDirname: rootDirname, maxParallelCount: maxParallelCount /* <- TODO: [🪂] */, isVerbose: isVerbose }))];
5269
5767
  case 2:
5270
5768
  partialknowledgePiecesPrepared = _c.sent();
5271
5769
  knowledgePiecesPrepared = partialknowledgePiecesPrepared.map(function (piece) { return (__assign(__assign({}, piece), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
@@ -5273,8 +5771,8 @@ function preparePipeline(pipeline, options) {
5273
5771
  parameters: parameters,
5274
5772
  templates: templates,
5275
5773
  knowledgePiecesCount: knowledgePiecesPrepared.length,
5276
- }, {
5277
- llmTools: llmToolsWithUsage,
5774
+ }, __assign(__assign({}, tools), { llm: llmToolsWithUsage }), {
5775
+ rootDirname: rootDirname,
5278
5776
  maxParallelCount: maxParallelCount /* <- TODO: [🪂] */,
5279
5777
  isVerbose: isVerbose,
5280
5778
  })];
@@ -5297,36 +5795,10 @@ function preparePipeline(pipeline, options) {
5297
5795
  * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
5298
5796
  */
5299
5797
 
5300
- /**
5301
- * Tests if given string is valid URL.
5302
- *
5303
- * Note: This does not check if the file exists only if the path is valid
5304
- * @public exported from `@promptbook/utils`
5305
- */
5306
- function isValidFilePath(filePath) {
5307
- if (typeof filePath !== 'string') {
5308
- return false;
5309
- }
5310
- var filePathSlashes = filePath.split('\\').join('/');
5311
- // Absolute Unix path: /hello.txt
5312
- if (/^(\/)/i.test(filePathSlashes)) {
5313
- return true;
5314
- }
5315
- // Absolute Windows path: /hello.txt
5316
- if (/^([A-Z]{1,2}:\/?)\//i.test(filePathSlashes)) {
5317
- return true;
5318
- }
5319
- // Relative path: ./hello.txt
5320
- if (/^(\.\.?\/)+/i.test(filePathSlashes)) {
5321
- return true;
5322
- }
5323
- return false;
5324
- }
5325
-
5326
5798
  /**
5327
5799
  * Parses the knowledge command
5328
5800
  *
5329
- * @see ./KNOWLEDGE-README.md for more details
5801
+ * @see `documentationUrl` for more details
5330
5802
  * @private within the commands folder
5331
5803
  */
5332
5804
  var knowledgeCommandParser = {
@@ -5344,7 +5816,7 @@ var knowledgeCommandParser = {
5344
5816
  */
5345
5817
  description: "Tells promptbook which external knowledge to use",
5346
5818
  /**
5347
- * Link to discussion
5819
+ * Link to documentation
5348
5820
  */
5349
5821
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/41',
5350
5822
  /**
@@ -5366,7 +5838,7 @@ var knowledgeCommandParser = {
5366
5838
  if (sourceContent === '') {
5367
5839
  throw new ParseError("Source is not defined");
5368
5840
  }
5369
- // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
5841
+ // TODO: [main] !!!! Following checks should be applied every link in the `sourceContent`
5370
5842
  if (sourceContent.startsWith('http://')) {
5371
5843
  throw new ParseError("Source is not secure");
5372
5844
  }
@@ -5388,11 +5860,8 @@ var knowledgeCommandParser = {
5388
5860
  */
5389
5861
  $applyToPipelineJson: function (command, $pipelineJson) {
5390
5862
  var sourceContent = command.sourceContent;
5391
- var name = 'source-' + sha256(hexEncoder.parse(JSON.stringify(sourceContent))).toString( /* hex */);
5392
- // <- TODO: [🥬] Encapsulate sha256 to some private utility function
5393
- // <- TODO: This should be replaced with a better name later in preparation (done with some propper LLM summarization)
5394
5863
  $pipelineJson.knowledgeSources.push({
5395
- name: name,
5864
+ name: sourceContentToName(sourceContent),
5396
5865
  sourceContent: sourceContent,
5397
5866
  });
5398
5867
  },
@@ -5422,7 +5891,7 @@ var knowledgeCommandParser = {
5422
5891
  /**
5423
5892
  * Parses the template command
5424
5893
  *
5425
- * @see ./TEMPLATE-README.md for more details
5894
+ * @see `documentationUrl` for more details
5426
5895
  * @private within the commands folder
5427
5896
  */
5428
5897
  var templateCommandParser = {
@@ -5458,7 +5927,7 @@ var templateCommandParser = {
5458
5927
  */
5459
5928
  description: "What should the code template template do",
5460
5929
  /**
5461
- * Link to discussion
5930
+ * Link to documentation
5462
5931
  */
5463
5932
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/64',
5464
5933
  /**
@@ -5683,7 +6152,7 @@ function parseNumber(value) {
5683
6152
  /**
5684
6153
  * Parses the expect command
5685
6154
  *
5686
- * @see ./EXPECT-README.md for more details
6155
+ * @see `documentationUrl` for more details
5687
6156
  * @private within the commands folder
5688
6157
  */
5689
6158
  var expectCommandParser = {
@@ -5701,7 +6170,7 @@ var expectCommandParser = {
5701
6170
  */
5702
6171
  description: spaceTrim("\n Expect command describes the desired output of the template (after post-processing)\n It can set limits for the maximum/minimum length of the output, measured in characters, words, sentences, paragraphs or some other shape of the output.\n "),
5703
6172
  /**
5704
- * Link to discussion
6173
+ * Link to documentation
5705
6174
  */
5706
6175
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/30',
5707
6176
  /**
@@ -5808,98 +6277,28 @@ var expectCommandParser = {
5808
6277
  if ($templateJson.expectations[unit].max !== undefined) {
5809
6278
  throw new ParseError("Already defined maximum ".concat($templateJson.expectations[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5810
6279
  }
5811
- $templateJson.expectations[unit].max = command.amount;
5812
- }
5813
- },
5814
- /**
5815
- * Converts the FORMAT command back to string
5816
- *
5817
- * Note: This is used in `pipelineJsonToString` utility
5818
- */
5819
- stringify: function (command) {
5820
- keepUnused(command);
5821
- return "---"; // <- TODO: [🛋] Implement
5822
- },
5823
- /**
5824
- * Reads the FORMAT command from the `TemplateJson`
5825
- *
5826
- * Note: This is used in `pipelineJsonToString` utility
5827
- */
5828
- takeFromTemplateJson: function ($templateJson) {
5829
- keepUnused($templateJson);
5830
- throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5831
- },
5832
- };
5833
-
5834
- /**
5835
- * @@@
5836
- *
5837
- * @param text @@@
5838
- * @returns @@@
5839
- * @example 'HELLO_WORLD'
5840
- * @example 'I_LOVE_PROMPTBOOK'
5841
- * @public exported from `@promptbook/utils`
5842
- */
5843
- function normalizeTo_SCREAMING_CASE(text) {
5844
- var e_1, _a;
5845
- var charType;
5846
- var lastCharType = 'OTHER';
5847
- var normalizedName = '';
5848
- try {
5849
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5850
- var char = text_1_1.value;
5851
- var normalizedChar = void 0;
5852
- if (/^[a-z]$/.test(char)) {
5853
- charType = 'LOWERCASE';
5854
- normalizedChar = char.toUpperCase();
5855
- }
5856
- else if (/^[A-Z]$/.test(char)) {
5857
- charType = 'UPPERCASE';
5858
- normalizedChar = char;
5859
- }
5860
- else if (/^[0-9]$/.test(char)) {
5861
- charType = 'NUMBER';
5862
- normalizedChar = char;
5863
- }
5864
- else if (/^\/$/.test(char)) {
5865
- charType = 'SLASH';
5866
- normalizedChar = char;
5867
- }
5868
- else {
5869
- charType = 'OTHER';
5870
- normalizedChar = '_';
5871
- }
5872
- if (charType !== lastCharType &&
5873
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
5874
- !(lastCharType === 'NUMBER') &&
5875
- !(charType === 'NUMBER')) {
5876
- normalizedName += '_';
5877
- }
5878
- normalizedName += normalizedChar;
5879
- lastCharType = charType;
5880
- }
5881
- }
5882
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5883
- finally {
5884
- try {
5885
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
6280
+ $templateJson.expectations[unit].max = command.amount;
5886
6281
  }
5887
- finally { if (e_1) throw e_1.error; }
5888
- }
5889
- normalizedName = normalizedName.replace(/_+/g, '_');
5890
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
5891
- normalizedName = normalizedName.replace(/^_/, '');
5892
- normalizedName = normalizedName.replace(/_$/, '');
5893
- return normalizedName;
5894
- }
5895
- /**
5896
- * TODO: Tests
5897
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
5898
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
5899
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
5900
- * > expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
5901
- * TODO: [🌺] Use some intermediate util splitWords
5902
- */
6282
+ },
6283
+ /**
6284
+ * Converts the FORMAT command back to string
6285
+ *
6286
+ * Note: This is used in `pipelineJsonToString` utility
6287
+ */
6288
+ stringify: function (command) {
6289
+ keepUnused(command);
6290
+ return "---"; // <- TODO: [🛋] Implement
6291
+ },
6292
+ /**
6293
+ * Reads the FORMAT command from the `TemplateJson`
6294
+ *
6295
+ * Note: This is used in `pipelineJsonToString` utility
6296
+ */
6297
+ takeFromTemplateJson: function ($templateJson) {
6298
+ keepUnused($templateJson);
6299
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
6300
+ },
6301
+ };
5903
6302
 
5904
6303
  /**
5905
6304
  * @@@
@@ -5965,6 +6364,22 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5965
6364
  * TODO: [🌺] Use some intermediate util splitWords
5966
6365
  */
5967
6366
 
6367
+ /**
6368
+ * Removes emojis from a string and fix whitespaces
6369
+ *
6370
+ * @param text with emojis
6371
+ * @returns text without emojis
6372
+ * @public exported from `@promptbook/utils`
6373
+ */
6374
+ function removeEmojis(text) {
6375
+ // Replace emojis (and also ZWJ sequence) with hyphens
6376
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
6377
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
6378
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
6379
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
6380
+ return text;
6381
+ }
6382
+
5968
6383
  /**
5969
6384
  * Removes quotes from a string
5970
6385
  *
@@ -6071,7 +6486,7 @@ function validateParameterName(parameterName) {
6071
6486
  *
6072
6487
  * Note: @@@ This command is used as foreach for new commands - it should NOT be used in any `.ptbk.md` file
6073
6488
  *
6074
- * @see ./FOREACH-README.md for more details <- TODO: @@@ Write theese README files OR remove this link + add annotation here (to all commands)
6489
+ * @see `documentationUrl` for more details
6075
6490
  * @private within the commands folder
6076
6491
  */
6077
6492
  var foreachCommandParser = {
@@ -6093,7 +6508,7 @@ var foreachCommandParser = {
6093
6508
  */
6094
6509
  description: "@@",
6095
6510
  /**
6096
- * Link to discussion
6511
+ * Link to documentation
6097
6512
  */
6098
6513
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
6099
6514
  /**
@@ -6101,8 +6516,10 @@ var foreachCommandParser = {
6101
6516
  */
6102
6517
  examples: [
6103
6518
  'FOREACH Text Line `{customers}` -> `{customer}`',
6104
- 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6105
- 'EACH Csv Cell `{customers}` -> `{subformat}`',
6519
+ 'FOREACH Csv Cell `{customers}` -> `{cell}`',
6520
+ 'FOREACH Csv Row `{customers}` -> `{firstName}`, `{lastName}`, `+{email}`',
6521
+ 'FOR Text Line `{customers}` -> `{customer}`',
6522
+ 'EACH Text Line `{customers}` -> `{customer}`',
6106
6523
  ],
6107
6524
  /**
6108
6525
  * Parses the FOREACH command
@@ -6136,20 +6553,49 @@ var foreachCommandParser = {
6136
6553
  throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6137
6554
  }
6138
6555
  var parameterName = validateParameterName(parameterNameArg);
6139
- var subparameterNames = args
6556
+ var outputSubparameterName = null;
6557
+ // TODO: [4] DRY
6558
+ var inputSubparameterNames = args
6140
6559
  .slice(4)
6141
6560
  .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6561
+ .filter(function (parameterName) { return !parameterName.includes('+'); })
6142
6562
  .filter(function (parameterName) { return parameterName !== ''; })
6143
6563
  .map(validateParameterName);
6144
- if (subparameterNames.length === 0) {
6145
- throw new ParseError("FOREACH command must have at least one subparameter");
6564
+ // TODO: [4] DRY
6565
+ var outputSubparameterNames = args
6566
+ .slice(4)
6567
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6568
+ .filter(function (parameterName) { return parameterName.includes('+'); })
6569
+ .map(function (parameterName) { return parameterName.split('+').join(''); })
6570
+ .map(validateParameterName);
6571
+ if (outputSubparameterNames.length === 1) {
6572
+ outputSubparameterName = outputSubparameterNames[0];
6573
+ }
6574
+ else if (outputSubparameterNames.length > 1) {
6575
+ throw new ParseError("FOREACH command can not have more than one output subparameter");
6576
+ }
6577
+ if (inputSubparameterNames.length === 0) {
6578
+ throw new ParseError("FOREACH command must have at least one input subparameter");
6579
+ }
6580
+ if (outputSubparameterName === null) {
6581
+ // TODO: Following code should be unhardcoded from here and moved to the format definition
6582
+ if (formatName === 'CSV' && subformatName === 'CELL') {
6583
+ outputSubparameterName = 'newCell';
6584
+ }
6585
+ else if (formatName === 'TEXT' && subformatName === 'LINE') {
6586
+ outputSubparameterName = 'newLine';
6587
+ }
6588
+ else {
6589
+ throw new ParseError(spaceTrim("\n FOREACH ".concat(formatName, " ").concat(subformatName, " must specify output subparameter\n\n Correct example:\n - FOREACH ").concat(formatName, " ").concat(subformatName, " {").concat(parameterName, "} -> {inputSubparameterName1}, {inputSubparameterName2}, +{outputSubparameterName}\n\n ")));
6590
+ }
6146
6591
  }
6147
6592
  return {
6148
6593
  type: 'FOREACH',
6149
6594
  formatName: formatName,
6150
6595
  subformatName: subformatName,
6151
6596
  parameterName: parameterName,
6152
- subparameterNames: subparameterNames,
6597
+ inputSubparameterNames: inputSubparameterNames,
6598
+ outputSubparameterName: outputSubparameterName,
6153
6599
  };
6154
6600
  },
6155
6601
  /**
@@ -6158,10 +6604,16 @@ var foreachCommandParser = {
6158
6604
  * Note: `$` is used to indicate that this function mutates given `templateJson`
6159
6605
  */
6160
6606
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
6161
- var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6607
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, inputSubparameterNames = command.inputSubparameterNames, outputSubparameterName = command.outputSubparameterName;
6162
6608
  // TODO: [🍭] Detect double use
6163
6609
  // TODO: [🍭] Detect usage with JOKER and don't allow it
6164
- $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6610
+ $templateJson.foreach = {
6611
+ formatName: formatName,
6612
+ subformatName: subformatName,
6613
+ parameterName: parameterName,
6614
+ inputSubparameterNames: inputSubparameterNames,
6615
+ outputSubparameterName: outputSubparameterName,
6616
+ };
6165
6617
  keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6166
6618
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
6167
6619
  },
@@ -6191,7 +6643,7 @@ var foreachCommandParser = {
6191
6643
  /**
6192
6644
  * Parses the format command
6193
6645
  *
6194
- * @see ./FORMAT-README.md for more details
6646
+ * @see `documentationUrl` for more details
6195
6647
  * @private within the commands folder
6196
6648
  */
6197
6649
  var formatCommandParser = {
@@ -6209,7 +6661,7 @@ var formatCommandParser = {
6209
6661
  */
6210
6662
  description: spaceTrim("\n Format command describes the desired output of the template (after post-processing)\n It can set limits for the maximum/minimum length of the output, measured in characters, words, sentences, paragraphs or some other shape of the output.\n "),
6211
6663
  /**
6212
- * Link to discussion
6664
+ * Link to documentation
6213
6665
  */
6214
6666
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/30',
6215
6667
  /**
@@ -6265,7 +6717,7 @@ var formatCommandParser = {
6265
6717
  /**
6266
6718
  * Parses the joker command
6267
6719
  *
6268
- * @see ./JOKER-README.md for more details
6720
+ * @see `documentationUrl` for more details
6269
6721
  * @private within the commands folder
6270
6722
  */
6271
6723
  var jokerCommandParser = {
@@ -6283,7 +6735,7 @@ var jokerCommandParser = {
6283
6735
  */
6284
6736
  description: "Joker parameter is used instead of executing the template result if jokers value meets the expectations requirements",
6285
6737
  /**
6286
- * Link to discussion
6738
+ * Link to documentation
6287
6739
  */
6288
6740
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/66',
6289
6741
  /**
@@ -6344,7 +6796,7 @@ var MODEL_VARIANTS = ['COMPLETION', 'CHAT', 'EMBEDDING' /* <- TODO [🏳] */ /*
6344
6796
  /**
6345
6797
  * Parses the model command
6346
6798
  *
6347
- * @see ./MODEL-README.md for more details
6799
+ * @see `documentationUrl` for more details
6348
6800
  * @private within the commands folder
6349
6801
  */
6350
6802
  var modelCommandParser = {
@@ -6362,7 +6814,7 @@ var modelCommandParser = {
6362
6814
  */
6363
6815
  description: "Tells which `modelRequirements` (for example which model) to use for the prompt template execution",
6364
6816
  /**
6365
- * Link to discussion
6817
+ * Link to documentation
6366
6818
  */
6367
6819
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/67',
6368
6820
  /**
@@ -6444,7 +6896,11 @@ var modelCommandParser = {
6444
6896
  // TODO: [🚜] DRY
6445
6897
  if ($templateJson.modelRequirements[command.key] !== undefined) {
6446
6898
  if ($templateJson.modelRequirements[command.key] === command.value) {
6447
- console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the template \"").concat($templateJson.title || $templateJson.name, "\""));
6899
+ console.warn("Multiple commands `MODEL ".concat({
6900
+ modelName: 'NAME',
6901
+ modelVariant: 'VARIANT',
6902
+ maxTokens: '???',
6903
+ }[command.key], " ").concat(command.value, "` in the template \"").concat($templateJson.title || $templateJson.name, "\""));
6448
6904
  }
6449
6905
  else {
6450
6906
  throw new ParseError(spaceTrim("\n Redefinition of MODEL `".concat(command.key, "` in the template \"").concat($templateJson.title || $templateJson.name, "\"\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($templateJson.modelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -6487,7 +6943,7 @@ var modelCommandParser = {
6487
6943
  /**
6488
6944
  * Parses the parameter command
6489
6945
  *
6490
- * @see ./PARAMETER-README.md for more details
6946
+ * @see `documentationUrl` for more details
6491
6947
  * @private within the commands folder
6492
6948
  */
6493
6949
  var parameterCommandParser = {
@@ -6512,7 +6968,7 @@ var parameterCommandParser = {
6512
6968
  */
6513
6969
  description: "Describes one parameter of the template",
6514
6970
  /**
6515
- * Link to discussion
6971
+ * Link to documentation
6516
6972
  */
6517
6973
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/68',
6518
6974
  /**
@@ -6597,7 +7053,7 @@ var parameterCommandParser = {
6597
7053
  /**
6598
7054
  * Parses the persona command
6599
7055
  *
6600
- * @see ./PERSONA-README.md for more details
7056
+ * @see `documentationUrl` for more details
6601
7057
  * @private within the commands folder
6602
7058
  */
6603
7059
  var personaCommandParser = {
@@ -6619,7 +7075,7 @@ var personaCommandParser = {
6619
7075
  */
6620
7076
  description: "Persona command is used to specify who the system is, it will be transformed into system message, top_t,...",
6621
7077
  /**
6622
- * Link to discussion
7078
+ * Link to documentation
6623
7079
  */
6624
7080
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/22',
6625
7081
  /**
@@ -6735,7 +7191,7 @@ function isValidJavascriptName(javascriptName) {
6735
7191
  /**
6736
7192
  * Parses the postprocess command
6737
7193
  *
6738
- * @see ./POSTPROCESS-README.md for more details
7194
+ * @see `documentationUrl` for more details
6739
7195
  * @private within the commands folder
6740
7196
  */
6741
7197
  var postprocessCommandParser = {
@@ -6754,7 +7210,7 @@ var postprocessCommandParser = {
6754
7210
  */
6755
7211
  description: "Defines the postprocess function to be used on the result from LLM and before the result is validated",
6756
7212
  /**
6757
- * Link to discussion
7213
+ * Link to documentation
6758
7214
  */
6759
7215
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/31',
6760
7216
  /**
@@ -6815,7 +7271,7 @@ var postprocessCommandParser = {
6815
7271
  /**
6816
7272
  * Parses the PROMPTBOOK_VERSION command
6817
7273
  *
6818
- * @see ./PROMPTBOOK_VERSION-README.md for more details
7274
+ * @see `documentationUrl` for more details
6819
7275
  * @private within the commands folder
6820
7276
  */
6821
7277
  var promptbookVersionCommandParser = {
@@ -6834,7 +7290,7 @@ var promptbookVersionCommandParser = {
6834
7290
  */
6835
7291
  description: "Which version of the promptbook is the .ptbk.md using",
6836
7292
  /**
6837
- * Link to discussion
7293
+ * Link to documentation
6838
7294
  */
6839
7295
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/69',
6840
7296
  /**
@@ -6893,7 +7349,7 @@ var promptbookVersionCommandParser = {
6893
7349
  /**
6894
7350
  * Parses the url command
6895
7351
  *
6896
- * @see ./URL-README.md for more details
7352
+ * @see `documentationUrl` for more details
6897
7353
  * @private within the commands folder
6898
7354
  */
6899
7355
  var urlCommandParser = {
@@ -6916,7 +7372,7 @@ var urlCommandParser = {
6916
7372
  */
6917
7373
  description: "Declares unique URL for the pipeline",
6918
7374
  /**
6919
- * Link to discussion
7375
+ * Link to documentation
6920
7376
  */
6921
7377
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/70',
6922
7378
  /**
@@ -6996,7 +7452,7 @@ var urlCommandParser = {
6996
7452
  /**
6997
7453
  * Parses the action command
6998
7454
  *
6999
- * @see ./ACTION-README.md for more details
7455
+ * @see `documentationUrl` for more details
7000
7456
  * @private within the commands folder
7001
7457
  */
7002
7458
  var actionCommandParser = {
@@ -7014,7 +7470,7 @@ var actionCommandParser = {
7014
7470
  */
7015
7471
  description: "Actions influences from the pipeline or template into external world. Like turning on a light, sending an email, etc.",
7016
7472
  /**
7017
- * Link to discussion
7473
+ * Link to documentation
7018
7474
  */
7019
7475
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/72',
7020
7476
  /**
@@ -7066,7 +7522,7 @@ var actionCommandParser = {
7066
7522
  /**
7067
7523
  * Parses the instrument command
7068
7524
  *
7069
- * @see ./INSTRUMENT-README.md for more details
7525
+ * @see `documentationUrl` for more details
7070
7526
  * @private within the commands folder
7071
7527
  */
7072
7528
  var instrumentCommandParser = {
@@ -7084,7 +7540,7 @@ var instrumentCommandParser = {
7084
7540
  */
7085
7541
  description: "Instrument command is used to specify the instrument to be used in the pipeline or template like search, calculate, etc.",
7086
7542
  /**
7087
- * Link to discussion
7543
+ * Link to documentation
7088
7544
  */
7089
7545
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/71',
7090
7546
  /**
@@ -7139,7 +7595,7 @@ var instrumentCommandParser = {
7139
7595
  *
7140
7596
  * Note: @@@ This command is used as boilerplate for new commands - it should NOT be used in any `.ptbk.md` file
7141
7597
  *
7142
- * @see ./BOILERPLATE-README.md for more details <- TODO: @@@ Write theese README files OR remove this link + add annotation here (to all commands)
7598
+ * @see `documentationUrl` for more details
7143
7599
  * @private within the commands folder
7144
7600
  */
7145
7601
  var boilerplateCommandParser = {
@@ -7161,7 +7617,7 @@ var boilerplateCommandParser = {
7161
7617
  */
7162
7618
  description: "@@",
7163
7619
  /**
7164
- * Link to discussion
7620
+ * Link to documentation
7165
7621
  */
7166
7622
  documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
7167
7623
  /**
@@ -7671,6 +8127,30 @@ function removeContentComments(content) {
7671
8127
  return spaceTrim$1(content.replace(/<!--(.*?)-->/gs, ''));
7672
8128
  }
7673
8129
 
8130
+ /**
8131
+ * @@@
8132
+ *
8133
+ * @param value @@@
8134
+ * @returns @@@
8135
+ * @example @@@
8136
+ * @public exported from `@promptbook/utils`
8137
+ */
8138
+ function titleToName(value) {
8139
+ if (isValidUrl(value)) {
8140
+ value = value.replace(/^https?:\/\//, '');
8141
+ value = value.replace(/\.html$/, '');
8142
+ }
8143
+ else if (isValidFilePath(value)) {
8144
+ value = basename(value);
8145
+ // Note: Keeping extension in the name
8146
+ }
8147
+ value = value.split('/').join('-');
8148
+ value = removeEmojis(value);
8149
+ value = normalizeToKebabCase(value);
8150
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
8151
+ return value;
8152
+ }
8153
+
7674
8154
  /**
7675
8155
  * Compile pipeline from string (markdown) format to JSON format synchronously
7676
8156
  *
@@ -7983,7 +8463,7 @@ function pipelineStringToJsonSync(pipelineString) {
7983
8463
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7984
8464
  }
7985
8465
  /**
7986
- * TODO:[main] !!!! Warn if used only sync version
8466
+ * TODO: [main] !!!! Warn if used only sync version
7987
8467
  * TODO: [🚞] Report here line/column of error
7988
8468
  * TODO: Use spaceTrim more effectively
7989
8469
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -8005,22 +8485,23 @@ function pipelineStringToJsonSync(pipelineString) {
8005
8485
  * Note: This function acts as compilation process
8006
8486
  *
8007
8487
  * @param pipelineString {Promptbook} in string markdown format (.ptbk.md)
8488
+ * @param tools - Tools for the preparation and scraping - if not provided together with `llm`, the preparation will be skipped
8008
8489
  * @param options - Options and tools for the compilation
8009
8490
  * @returns {Promptbook} compiled in JSON format (.ptbk.json)
8010
8491
  * @throws {ParseError} if the promptbook string is not valid
8011
8492
  * @public exported from `@promptbook/core`
8012
8493
  */
8013
- function pipelineStringToJson(pipelineString, options) {
8014
- if (options === void 0) { options = { llmTools: null }; }
8494
+ function pipelineStringToJson(pipelineString, tools, options) {
8015
8495
  return __awaiter(this, void 0, void 0, function () {
8016
- var llmTools, pipelineJson;
8496
+ var pipelineJson;
8017
8497
  return __generator(this, function (_a) {
8018
8498
  switch (_a.label) {
8019
8499
  case 0:
8020
- llmTools = options.llmTools;
8021
8500
  pipelineJson = pipelineStringToJsonSync(pipelineString);
8022
- if (!(llmTools !== null)) return [3 /*break*/, 2];
8023
- return [4 /*yield*/, preparePipeline(pipelineJson, { llmTools: llmTools })];
8501
+ if (!(tools !== undefined && tools.llm !== undefined)) return [3 /*break*/, 2];
8502
+ return [4 /*yield*/, preparePipeline(pipelineJson, tools, options || {
8503
+ rootDirname: null,
8504
+ })];
8024
8505
  case 1:
8025
8506
  pipelineJson = _a.sent();
8026
8507
  _a.label = 2;
@@ -8228,6 +8709,38 @@ function stringifyPipelineJson(pipeline) {
8228
8709
  * TODO: [🍙] Make some standard order of json properties
8229
8710
  */
8230
8711
 
8712
+ /**
8713
+ * Delagates the user interaction to a async callback function
8714
+ * You need to provide your own implementation of this callback function and its bind to UI.
8715
+ *
8716
+ * @public exported from `@promptbook/core`
8717
+ */
8718
+ var CallbackInterfaceTools = /** @class */ (function () {
8719
+ function CallbackInterfaceTools(options) {
8720
+ this.options = options;
8721
+ }
8722
+ /**
8723
+ * Trigger the custom callback function
8724
+ */
8725
+ CallbackInterfaceTools.prototype.promptDialog = function (options) {
8726
+ return __awaiter(this, void 0, void 0, function () {
8727
+ var answer;
8728
+ return __generator(this, function (_a) {
8729
+ switch (_a.label) {
8730
+ case 0: return [4 /*yield*/, this.options.callback(options)];
8731
+ case 1:
8732
+ answer = _a.sent();
8733
+ if (this.options.isVerbose) {
8734
+ console.info(spaceTrim$1(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
8735
+ }
8736
+ return [2 /*return*/, answer];
8737
+ }
8738
+ });
8739
+ });
8740
+ };
8741
+ return CallbackInterfaceTools;
8742
+ }());
8743
+
8231
8744
  /**
8232
8745
  * Pretty print an embedding vector for logging
8233
8746
  *
@@ -8303,88 +8816,6 @@ function usageToHuman(usage) {
8303
8816
  * TODO: [🏛] Maybe make some markdown builder
8304
8817
  */
8305
8818
 
8306
- /**
8307
- * Delagates the user interaction to a async callback function
8308
- * You need to provide your own implementation of this callback function and its bind to UI.
8309
- *
8310
- * @public exported from `@promptbook/core`
8311
- */
8312
- var CallbackInterfaceTools = /** @class */ (function () {
8313
- function CallbackInterfaceTools(options) {
8314
- this.options = options;
8315
- }
8316
- /**
8317
- * Trigger the custom callback function
8318
- */
8319
- CallbackInterfaceTools.prototype.promptDialog = function (options) {
8320
- return __awaiter(this, void 0, void 0, function () {
8321
- var answer;
8322
- return __generator(this, function (_a) {
8323
- switch (_a.label) {
8324
- case 0: return [4 /*yield*/, this.options.callback(options)];
8325
- case 1:
8326
- answer = _a.sent();
8327
- if (this.options.isVerbose) {
8328
- console.info(spaceTrim$1(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
8329
- }
8330
- return [2 /*return*/, answer];
8331
- }
8332
- });
8333
- });
8334
- };
8335
- return CallbackInterfaceTools;
8336
- }());
8337
-
8338
- /**
8339
- * @@@
8340
- *
8341
- * Note: `$` is used to indicate that this function is not a pure function - it access global scope
8342
- *
8343
- * @private internal function of `$Register`
8344
- */
8345
- function $getGlobalScope() {
8346
- return Function('return this')();
8347
- }
8348
-
8349
- /**
8350
- * Register is @@@
8351
- *
8352
- * Note: `$` is used to indicate that this function is not a pure function - it accesses and adds variables in global scope.
8353
- *
8354
- * @private internal utility, exported are only signleton instances of this class
8355
- */
8356
- var $Register = /** @class */ (function () {
8357
- function $Register(storageName) {
8358
- this.storageName = storageName;
8359
- storageName = "_promptbook_".concat(storageName);
8360
- var globalScope = $getGlobalScope();
8361
- if (globalScope[storageName] === undefined) {
8362
- globalScope[storageName] = [];
8363
- }
8364
- else if (!Array.isArray(globalScope[storageName])) {
8365
- throw new UnexpectedError("Expected (global) ".concat(storageName, " to be an array, but got ").concat(typeof globalScope[storageName]));
8366
- }
8367
- this.storage = globalScope[storageName];
8368
- }
8369
- $Register.prototype.list = function () {
8370
- // <- TODO: ReadonlyDeep<Array<TRegistered>>
8371
- return this.storage;
8372
- };
8373
- $Register.prototype.register = function (registered) {
8374
- // <- TODO: What to return here
8375
- var packageName = registered.packageName, className = registered.className;
8376
- var existingRegistrationIndex = this.storage.findIndex(function (item) { return item.packageName === packageName && item.className === className; });
8377
- var existingRegistration = this.storage[existingRegistrationIndex];
8378
- if (!existingRegistration) {
8379
- this.storage.push(registered);
8380
- }
8381
- else {
8382
- this.storage[existingRegistrationIndex] = registered;
8383
- }
8384
- };
8385
- return $Register;
8386
- }());
8387
-
8388
8819
  /**
8389
8820
  * @@@
8390
8821
  *
@@ -8393,6 +8824,9 @@ var $Register = /** @class */ (function () {
8393
8824
  * @public exported from `@promptbook/core`
8394
8825
  */
8395
8826
  var $llmToolsMetadataRegister = new $Register('llm_tools_metadata');
8827
+ /**
8828
+ * TODO: [®] DRY Register logic
8829
+ */
8396
8830
 
8397
8831
  /**
8398
8832
  * @@@
@@ -8402,13 +8836,16 @@ var $llmToolsMetadataRegister = new $Register('llm_tools_metadata');
8402
8836
  * @public exported from `@promptbook/core`
8403
8837
  */
8404
8838
  var $llmToolsRegister = new $Register('llm_execution_tools_constructors');
8839
+ /**
8840
+ * TODO: [®] DRY Register logic
8841
+ */
8405
8842
 
8406
8843
  /**
8407
8844
  * Creates a message with all registered LLM tools
8408
8845
  *
8409
8846
  * Note: This function is used to create a (error) message when there is no constructor for some LLM provider
8410
8847
  *
8411
- * @private internal function of `createLlmToolsFromConfiguration` and `createLlmToolsFromEnv`
8848
+ * @private internal function of `createLlmToolsFromConfiguration` and `$provideLlmToolsFromEnv`
8412
8849
  */
8413
8850
  function $registeredLlmToolsMessage() {
8414
8851
  var e_1, _a, e_2, _b;
@@ -8500,6 +8937,9 @@ function $registeredLlmToolsMessage() {
8500
8937
  })
8501
8938
  .join('\n')), "\n "); });
8502
8939
  }
8940
+ /**
8941
+ * TODO: [®] DRY Register logic
8942
+ */
8503
8943
 
8504
8944
  /**
8505
8945
  * @@@
@@ -8527,12 +8967,13 @@ function createLlmToolsFromConfiguration(configuration, options) {
8527
8967
  return joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(llmTools), false));
8528
8968
  }
8529
8969
  /**
8530
- * TODO: [🎌] Togethere with `createLlmToolsFromConfiguration` + 'EXECUTION_TOOLS_CLASSES' gets to `@promptbook/core` ALL model providers, make this more efficient
8970
+ * TODO: [🎌] Together with `createLlmToolsFromConfiguration` + 'EXECUTION_TOOLS_CLASSES' gets to `@promptbook/core` ALL model providers, make this more efficient
8531
8971
  * TODO: [🧠][🎌] Dynamically install required providers
8532
8972
  * TODO: @@@ write discussion about this - wizzard
8533
8973
  * TODO: [🧠][🍛] Which name is better `createLlmToolsFromConfig` or `createLlmToolsFromConfiguration`?
8534
8974
  * TODO: [🧠] Is there some meaningfull way how to test this util
8535
8975
  * TODO: This should be maybe not under `_common` but under `utils`
8976
+ * TODO: [®] DRY Register logic
8536
8977
  */
8537
8978
 
8538
8979
  /**
@@ -8611,11 +9052,7 @@ function $currentDate() {
8611
9052
  function cacheLlmTools(llmTools, options) {
8612
9053
  var _this = this;
8613
9054
  if (options === void 0) { options = {}; }
8614
- var _a = options.storage, storage = _a === void 0 ? new MemoryStorage() : _a,
8615
- // <- TODO: [🧱] Implement in a functional (not new Class) way
8616
- _b = options.isReloaded,
8617
- // <- TODO: [🧱] Implement in a functional (not new Class) way
8618
- isReloaded = _b === void 0 ? false : _b;
9055
+ var _a = options.storage, storage = _a === void 0 ? new MemoryStorage() : _a, _b = options.isReloaded, isReloaded = _b === void 0 ? false : _b;
8619
9056
  var proxyTools = __assign(__assign({}, llmTools), {
8620
9057
  // <- Note: [🥫]
8621
9058
  get title() {
@@ -8765,9 +9202,9 @@ function limitTotalUsage(llmTools, options) {
8765
9202
  */
8766
9203
 
8767
9204
  /**
8768
- * @@@ registration1 of default configuration for Anthropic Claude
9205
+ * Registration of LLM provider metadata
8769
9206
  *
8770
- * Note: [🏐] Configurations registrations are done in @@@ BUT constructor @@@
9207
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available LLM tools
8771
9208
  *
8772
9209
  * @public exported from `@promptbook/core`
8773
9210
  * @public exported from `@promptbook/cli`
@@ -8805,9 +9242,9 @@ var _AnthropicClaudeMetadataRegistration = $llmToolsMetadataRegister.register({
8805
9242
  });
8806
9243
 
8807
9244
  /**
8808
- * @@@ registration1 of default configuration for Azure Open AI
9245
+ * Registration of LLM provider metadata
8809
9246
  *
8810
- * Note: [🏐] Configurations registrations are done in @@@ BUT constructor @@@
9247
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available LLM tools
8811
9248
  *
8812
9249
  * @public exported from `@promptbook/core`
8813
9250
  * @public exported from `@promptbook/cli`
@@ -8844,16 +9281,16 @@ var _AzureOpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
8844
9281
  else if (typeof env.AZUREOPENAI_RESOURCE_NAME === 'string' ||
8845
9282
  typeof env.AZUREOPENAI_DEPLOYMENT_NAME === 'string' ||
8846
9283
  typeof env.AZUREOPENAI_API_KEY === 'string') {
8847
- throw new Error(spaceTrim("\n You must provide all of the following environment variables:\n \n - AZUREOPENAI_RESOURCE_NAME (".concat(typeof env.AZUREOPENAI_RESOURCE_NAME === 'string' ? 'defined' : 'not defined', ")\n - AZUREOPENAI_DEPLOYMENT_NAME (").concat(typeof env.AZUREOPENAI_DEPLOYMENT_NAME === 'string' ? 'defined' : 'not defined', ")\n - AZUREOPENAI_API_KEY (").concat(typeof env.AZUREOPENAI_API_KEY === 'string' ? 'defined' : 'not defined', ") \n ")));
9284
+ throw new Error(spaceTrim("\n You must provide all of the following environment variables:\n\n - AZUREOPENAI_RESOURCE_NAME (".concat(typeof env.AZUREOPENAI_RESOURCE_NAME === 'string' ? 'defined' : 'not defined', ")\n - AZUREOPENAI_DEPLOYMENT_NAME (").concat(typeof env.AZUREOPENAI_DEPLOYMENT_NAME === 'string' ? 'defined' : 'not defined', ")\n - AZUREOPENAI_API_KEY (").concat(typeof env.AZUREOPENAI_API_KEY === 'string' ? 'defined' : 'not defined', ")\n ")));
8848
9285
  }
8849
9286
  return null;
8850
9287
  },
8851
9288
  });
8852
9289
 
8853
9290
  /**
8854
- * @@@ registration1 of default configuration for Open AI
9291
+ * Registration of LLM provider metadata
8855
9292
  *
8856
- * Note: [🏐] Configurations registrations are done in @@@ BUT constructor @@@
9293
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available LLM tools
8857
9294
  *
8858
9295
  * @public exported from `@promptbook/core`
8859
9296
  * @public exported from `@promptbook/cli`
@@ -8887,6 +9324,126 @@ var _OpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
8887
9324
  },
8888
9325
  });
8889
9326
 
9327
+ /**
9328
+ * Metadata of the scraper
9329
+ *
9330
+ * @private within the scraper directory
9331
+ */
9332
+ var legacyDocumentScraperMetadata = $deepFreeze({
9333
+ title: 'LegacyDocument scraper',
9334
+ packageName: '@promptbook/legacy-documents',
9335
+ className: 'LegacyDocumentScraper',
9336
+ mimeTypes: ['application/msword', 'text/rtf'],
9337
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
9338
+ isAvilableInBrowser: false,
9339
+ requiredExecutables: ['!!!!!!'],
9340
+ }); /* <- TODO: [🤛] */
9341
+ /**
9342
+ * Registration of known scraper metadata
9343
+ *
9344
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available known scrapers
9345
+ *
9346
+ * @public exported from `@promptbook/core`
9347
+ * @public exported from `@promptbook/cli`
9348
+ */
9349
+ var _LegacyDocumentScraperMetadataRegistration = $scrapersMetadataRegister.register(legacyDocumentScraperMetadata);
9350
+
9351
+ /**
9352
+ * Metadata of the scraper
9353
+ *
9354
+ * @private within the scraper directory
9355
+ */
9356
+ var documentScraperMetadata = $deepFreeze({
9357
+ title: 'Document scraper',
9358
+ packageName: '@promptbook/documents',
9359
+ className: 'DocumentScraper',
9360
+ mimeTypes: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
9361
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
9362
+ isAvilableInBrowser: false,
9363
+ requiredExecutables: ['!!!!!!'],
9364
+ }); /* <- TODO: [🤛] */
9365
+ /**
9366
+ * Registration of known scraper metadata
9367
+ *
9368
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available known scrapers
9369
+ *
9370
+ * @public exported from `@promptbook/core`
9371
+ * @public exported from `@promptbook/cli`
9372
+ */
9373
+ var _DocumentScraperMetadataRegistration = $scrapersMetadataRegister.register(documentScraperMetadata);
9374
+
9375
+ /**
9376
+ * Metadata of the scraper
9377
+ *
9378
+ * @private within the scraper directory
9379
+ */
9380
+ var markdownScraperMetadata = $deepFreeze({
9381
+ title: 'Markdown scraper',
9382
+ packageName: '@promptbook/markdown-utils',
9383
+ className: 'MarkdownScraper',
9384
+ mimeTypes: ['text/markdown', 'text/plain'],
9385
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
9386
+ isAvilableInBrowser: true,
9387
+ requiredExecutables: ['!!!!!!'],
9388
+ }); /* <- TODO: [🤛] */
9389
+ /**
9390
+ * Registration of known scraper metadata
9391
+ *
9392
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available known scrapers
9393
+ *
9394
+ * @public exported from `@promptbook/core`
9395
+ * @public exported from `@promptbook/cli`
9396
+ */
9397
+ var _MarkdownScraperMetadataRegistration = $scrapersMetadataRegister.register(markdownScraperMetadata);
9398
+
9399
+ /**
9400
+ * Metadata of the scraper
9401
+ *
9402
+ * @private within the scraper directory
9403
+ */
9404
+ var pdfScraperMetadata = $deepFreeze({
9405
+ title: 'Pdf scraper',
9406
+ packageName: '@promptbook/pdf',
9407
+ className: 'PdfScraper',
9408
+ mimeTypes: ['application/pdf'],
9409
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
9410
+ isAvilableInBrowser: true,
9411
+ requiredExecutables: ['!!!!!!'],
9412
+ }); /* <- TODO: [🤛] */
9413
+ /**
9414
+ * Registration of known scraper metadata
9415
+ *
9416
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available known scrapers
9417
+ *
9418
+ * @public exported from `@promptbook/core`
9419
+ * @public exported from `@promptbook/cli`
9420
+ */
9421
+ var _PdfScraperMetadataRegistration = $scrapersMetadataRegister.register(pdfScraperMetadata);
9422
+
9423
+ /**
9424
+ * Metadata of the scraper
9425
+ *
9426
+ * @private within the scraper directory
9427
+ */
9428
+ var websiteScraperMetadata = $deepFreeze({
9429
+ title: 'Website scraper',
9430
+ packageName: '@promptbook/website-crawler',
9431
+ className: 'WebsiteScraper',
9432
+ mimeTypes: ['text/html'],
9433
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
9434
+ isAvilableInBrowser: false,
9435
+ requiredExecutables: ['!!!!!!'],
9436
+ }); /* <- TODO: [🤛] */
9437
+ /**
9438
+ * Registration of known scraper metadata
9439
+ *
9440
+ * Warning: This is not useful for the end user, it is just a side effect of the mechanism that handles all available known scrapers
9441
+ *
9442
+ * @public exported from `@promptbook/core`
9443
+ * @public exported from `@promptbook/cli`
9444
+ */
9445
+ var _WebsiteScraperMetadataRegistration = $scrapersMetadataRegister.register(websiteScraperMetadata);
9446
+
8890
9447
  /**
8891
9448
  * This class behaves like LocalStorage but separates keys by prefix
8892
9449
  *
@@ -9237,5 +9794,5 @@ function executionReportJsonToString(executionReportJson, options) {
9237
9794
  * TODO: [🧠] Should be in generated file GENERATOR_WARNING
9238
9795
  */
9239
9796
 
9240
- export { $llmToolsMetadataRegister, $llmToolsRegister, CLAIM, CallbackInterfaceTools, CollectionError, CsvFormatDefinition, DEFAULT_CSV_SETTINGS, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_VERBOSE, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, TemplateTypes, TextFormatDefinition, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
9797
+ export { $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, AbstractFormatError, CLAIM, CallbackInterfaceTools, CollectionError, CsvFormatDefinition, CsvFormatError, DEFAULT_CSV_SETTINGS, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_AUTO_INSTALLED, IS_VERBOSE, KnowledgeScrapeError, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, MissingToolsError, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, SCRAPE_CACHE_DIRNAME, TemplateTypes, TextFormatDefinition, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _DocumentScraperMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
9241
9798
  //# sourceMappingURL=index.es.js.map