@promptbook/core 0.92.0-9 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +140 -88
  2. package/esm/index.es.js +1020 -638
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/browser.index.d.ts +2 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +26 -14
  6. package/esm/typings/src/_packages/types.index.d.ts +6 -2
  7. package/esm/typings/src/collection/PipelineCollection.d.ts +0 -2
  8. package/esm/typings/src/collection/SimplePipelineCollection.d.ts +1 -1
  9. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +6 -6
  10. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +0 -2
  11. package/esm/typings/src/commands/FORMFACTOR/formfactorCommandParser.d.ts +1 -1
  12. package/esm/typings/src/commands/_BOILERPLATE/boilerplateCommandParser.d.ts +1 -1
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +36 -28
  14. package/esm/typings/src/config.d.ts +41 -11
  15. package/esm/typings/src/constants.d.ts +43 -2
  16. package/esm/typings/src/conversion/parsePipeline.d.ts +2 -2
  17. package/esm/typings/src/errors/0-BoilerplateError.d.ts +2 -2
  18. package/esm/typings/src/errors/CollectionError.d.ts +1 -1
  19. package/esm/typings/src/executables/$provideExecutablesForNode.d.ts +1 -1
  20. package/esm/typings/src/executables/apps/locateLibreoffice.d.ts +2 -1
  21. package/esm/typings/src/executables/apps/locatePandoc.d.ts +2 -1
  22. package/esm/typings/src/executables/locateApp.d.ts +2 -2
  23. package/esm/typings/src/executables/platforms/locateAppOnLinux.d.ts +2 -1
  24. package/esm/typings/src/executables/platforms/locateAppOnMacOs.d.ts +2 -1
  25. package/esm/typings/src/executables/platforms/locateAppOnWindows.d.ts +2 -1
  26. package/esm/typings/src/execution/AbstractTaskResult.d.ts +1 -1
  27. package/esm/typings/src/execution/CommonToolsOptions.d.ts +3 -3
  28. package/esm/typings/src/execution/ExecutionTask.d.ts +19 -1
  29. package/esm/typings/src/execution/LlmExecutionToolsConstructor.d.ts +2 -1
  30. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +4 -2
  31. package/esm/typings/src/execution/PromptbookFetch.d.ts +1 -1
  32. package/esm/typings/src/execution/ScriptExecutionTools.d.ts +1 -1
  33. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTaskResult.d.ts +12 -9
  34. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +13 -10
  35. package/esm/typings/src/execution/createPipelineExecutor/20-executeTask.d.ts +12 -9
  36. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatSubvalues.d.ts +15 -3
  37. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +21 -15
  38. package/esm/typings/src/execution/createPipelineExecutor/computeCosineSimilarity.d.ts +13 -0
  39. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +7 -6
  40. package/esm/typings/src/execution/createPipelineExecutor/getContextForTask.d.ts +5 -1
  41. package/esm/typings/src/execution/createPipelineExecutor/getExamplesForTask.d.ts +1 -1
  42. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTask.d.ts +12 -9
  43. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTask.d.ts +18 -5
  44. package/esm/typings/src/execution/createPipelineExecutor/knowledgePiecesToString.d.ts +9 -0
  45. package/esm/typings/src/execution/execution-report/ExecutionReportJson.d.ts +1 -1
  46. package/esm/typings/src/execution/execution-report/ExecutionReportString.d.ts +1 -1
  47. package/esm/typings/src/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +4 -4
  48. package/esm/typings/src/execution/utils/checkExpectations.d.ts +3 -3
  49. package/esm/typings/src/execution/utils/uncertainNumber.d.ts +3 -2
  50. package/esm/typings/src/execution/utils/usageToWorktime.d.ts +1 -1
  51. package/esm/typings/src/formats/_common/{FormatDefinition.d.ts → FormatParser.d.ts} +8 -6
  52. package/esm/typings/src/formats/_common/FormatSubvalueParser.d.ts +66 -0
  53. package/esm/typings/src/formats/csv/CsvFormatParser.d.ts +17 -0
  54. package/esm/typings/src/formats/csv/CsvSettings.d.ts +2 -2
  55. package/esm/typings/src/formats/csv/utils/csvParse.d.ts +12 -0
  56. package/esm/typings/src/formats/csv/utils/isValidCsvString.d.ts +1 -1
  57. package/esm/typings/src/formats/index.d.ts +2 -2
  58. package/esm/typings/src/formats/json/JsonFormatParser.d.ts +19 -0
  59. package/esm/typings/src/formats/json/utils/isValidJsonString.d.ts +1 -1
  60. package/esm/typings/src/formats/json/utils/jsonParse.d.ts +0 -3
  61. package/esm/typings/src/formats/text/{TextFormatDefinition.d.ts → TextFormatParser.d.ts} +7 -7
  62. package/esm/typings/src/formats/xml/XmlFormatParser.d.ts +19 -0
  63. package/esm/typings/src/formats/xml/utils/isValidXmlString.d.ts +1 -1
  64. package/esm/typings/src/formfactors/_boilerplate/BoilerplateFormfactorDefinition.d.ts +3 -2
  65. package/esm/typings/src/formfactors/_common/AbstractFormfactorDefinition.d.ts +16 -7
  66. package/esm/typings/src/formfactors/_common/FormfactorDefinition.d.ts +3 -1
  67. package/esm/typings/src/formfactors/_common/string_formfactor_name.d.ts +2 -1
  68. package/esm/typings/src/formfactors/chatbot/ChatbotFormfactorDefinition.d.ts +2 -2
  69. package/esm/typings/src/formfactors/completion/CompletionFormfactorDefinition.d.ts +29 -0
  70. package/esm/typings/src/formfactors/generator/GeneratorFormfactorDefinition.d.ts +2 -1
  71. package/esm/typings/src/formfactors/generic/GenericFormfactorDefinition.d.ts +2 -2
  72. package/esm/typings/src/formfactors/index.d.ts +33 -8
  73. package/esm/typings/src/formfactors/matcher/MatcherFormfactorDefinition.d.ts +4 -2
  74. package/esm/typings/src/formfactors/sheets/SheetsFormfactorDefinition.d.ts +3 -2
  75. package/esm/typings/src/formfactors/translator/TranslatorFormfactorDefinition.d.ts +3 -2
  76. package/esm/typings/src/high-level-abstractions/index.d.ts +2 -2
  77. package/esm/typings/src/llm-providers/_common/register/$llmToolsMetadataRegister.d.ts +3 -3
  78. package/esm/typings/src/llm-providers/_common/register/$llmToolsRegister.d.ts +3 -3
  79. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsConfigurationFromEnv.d.ts +4 -4
  80. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForTestingAndScriptsAndPlayground.d.ts +4 -3
  81. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsFromEnv.d.ts +18 -5
  82. package/esm/typings/src/llm-providers/_common/register/LlmToolsConfiguration.d.ts +11 -4
  83. package/esm/typings/src/llm-providers/_common/register/LlmToolsMetadata.d.ts +21 -42
  84. package/esm/typings/src/llm-providers/_common/register/LlmToolsOptions.d.ts +9 -2
  85. package/esm/typings/src/llm-providers/_common/register/createLlmToolsFromConfiguration.d.ts +13 -4
  86. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +10 -5
  87. package/esm/typings/src/llm-providers/_common/utils/cache/CacheLlmToolsOptions.d.ts +11 -3
  88. package/esm/typings/src/llm-providers/_common/utils/cache/cacheLlmTools.d.ts +3 -3
  89. package/esm/typings/src/llm-providers/_common/utils/count-total-usage/limitTotalUsage.d.ts +5 -5
  90. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +6 -0
  91. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  92. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +1 -1
  93. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +4 -4
  94. package/esm/typings/src/llm-providers/deepseek/deepseek-models.d.ts +1 -1
  95. package/esm/typings/src/llm-providers/google/google-models.d.ts +1 -1
  96. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +1 -1
  97. package/esm/typings/src/llm-providers/openai/openai-models.d.ts +1 -1
  98. package/esm/typings/src/llm-providers/openai/register-configuration.d.ts +2 -2
  99. package/esm/typings/src/llm-providers/openai/register-constructor.d.ts +2 -2
  100. package/esm/typings/src/migrations/migratePipeline.d.ts +9 -0
  101. package/esm/typings/src/other/templates/getBookTemplates.d.ts +2 -2
  102. package/esm/typings/src/pipeline/PipelineInterface/PipelineInterface.d.ts +3 -3
  103. package/esm/typings/src/pipeline/PipelineInterface/constants.d.ts +1 -1
  104. package/esm/typings/src/pipeline/PipelineInterface/getPipelineInterface.d.ts +1 -1
  105. package/esm/typings/src/pipeline/PipelineInterface/isPipelineImplementingInterface.d.ts +5 -4
  106. package/esm/typings/src/pipeline/PipelineInterface/isPipelineInterfacesEqual.d.ts +1 -1
  107. package/esm/typings/src/pipeline/PipelineJson/CommonTaskJson.d.ts +10 -7
  108. package/esm/typings/src/pipeline/PipelineJson/ParameterJson.d.ts +1 -1
  109. package/esm/typings/src/pipeline/PipelineJson/PipelineJson.d.ts +3 -2
  110. package/esm/typings/src/pipeline/PipelineString.d.ts +3 -1
  111. package/esm/typings/src/pipeline/book-notation.d.ts +2 -2
  112. package/esm/typings/src/postprocessing/utils/extractBlock.d.ts +1 -1
  113. package/esm/typings/src/postprocessing/utils/extractJsonBlock.d.ts +2 -2
  114. package/esm/typings/src/prepare/prepareTasks.d.ts +8 -5
  115. package/esm/typings/src/remote-server/openapi.d.ts +1 -1
  116. package/esm/typings/src/remote-server/socket-types/listModels/PromptbookServer_ListModels_Response.d.ts +1 -1
  117. package/esm/typings/src/remote-server/startRemoteServer.d.ts +1 -1
  118. package/esm/typings/src/remote-server/types/RemoteServerOptions.d.ts +7 -6
  119. package/esm/typings/src/scrapers/_boilerplate/BoilerplateScraper.d.ts +3 -3
  120. package/esm/typings/src/scrapers/_boilerplate/createBoilerplateScraper.d.ts +1 -1
  121. package/esm/typings/src/scrapers/_boilerplate/register-metadata.d.ts +1 -1
  122. package/esm/typings/src/scrapers/_common/Converter.d.ts +3 -1
  123. package/esm/typings/src/scrapers/_common/Scraper.d.ts +4 -3
  124. package/esm/typings/src/scrapers/_common/ScraperIntermediateSource.d.ts +4 -2
  125. package/esm/typings/src/scrapers/_common/prepareKnowledgePieces.d.ts +2 -2
  126. package/esm/typings/src/scrapers/_common/register/$provideFilesystemForNode.d.ts +2 -1
  127. package/esm/typings/src/scrapers/_common/register/$provideScrapersForBrowser.d.ts +6 -3
  128. package/esm/typings/src/scrapers/_common/register/$provideScrapersForNode.d.ts +3 -5
  129. package/esm/typings/src/scrapers/_common/register/$scrapersMetadataRegister.d.ts +3 -3
  130. package/esm/typings/src/scrapers/_common/register/$scrapersRegister.d.ts +3 -2
  131. package/esm/typings/src/scrapers/_common/register/ScraperAndConverterMetadata.d.ts +8 -5
  132. package/esm/typings/src/scrapers/_common/register/ScraperConstructor.d.ts +2 -1
  133. package/esm/typings/src/scrapers/_common/utils/getScraperIntermediateSource.d.ts +6 -5
  134. package/esm/typings/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +3 -1
  135. package/esm/typings/src/scrapers/document/createDocumentScraper.d.ts +1 -1
  136. package/esm/typings/src/scrapers/document-legacy/createLegacyDocumentScraper.d.ts +2 -1
  137. package/esm/typings/src/scrapers/markdown/createMarkdownScraper.d.ts +4 -1
  138. package/esm/typings/src/scrapers/markitdown/MarkitdownScraper.d.ts +1 -1
  139. package/esm/typings/src/scrapers/pdf/createPdfScraper.d.ts +2 -1
  140. package/esm/typings/src/scrapers/website/createWebsiteScraper.d.ts +3 -4
  141. package/esm/typings/src/scripting/javascript/JavascriptExecutionTools.d.ts +1 -1
  142. package/esm/typings/src/scripting/javascript/postprocessing-functions.d.ts +5 -1
  143. package/esm/typings/src/scripting/javascript/utils/preserve.d.ts +1 -1
  144. package/esm/typings/src/storage/_common/PromptbookStorage.d.ts +1 -1
  145. package/esm/typings/src/storage/file-cache-storage/FileCacheStorage.d.ts +12 -5
  146. package/esm/typings/src/storage/file-cache-storage/FileCacheStorageOptions.d.ts +4 -2
  147. package/esm/typings/src/storage/file-cache-storage/utils/nameToSubfolderPath.d.ts +2 -1
  148. package/esm/typings/src/storage/local-storage/getIndexedDbStorage.d.ts +11 -0
  149. package/esm/typings/src/storage/local-storage/utils/IndexedDbStorageOptions.d.ts +14 -0
  150. package/esm/typings/src/storage/local-storage/utils/makePromptbookStorageFromIndexedDb.d.ts +8 -0
  151. package/esm/typings/src/storage/local-storage/utils/makePromptbookStorageFromWebStorage.d.ts +2 -1
  152. package/esm/typings/src/types/IntermediateFilesStrategy.d.ts +2 -1
  153. package/esm/typings/src/types/ModelRequirements.d.ts +2 -2
  154. package/esm/typings/src/types/ModelVariant.d.ts +5 -5
  155. package/esm/typings/src/types/typeAliases.d.ts +22 -19
  156. package/esm/typings/src/utils/$Register.d.ts +8 -7
  157. package/esm/typings/src/utils/editable/edit-pipeline-string/addPipelineCommand.d.ts +2 -2
  158. package/esm/typings/src/utils/editable/edit-pipeline-string/deflatePipeline.d.ts +4 -1
  159. package/esm/typings/src/utils/editable/utils/isFlatPipeline.d.ts +2 -1
  160. package/esm/typings/src/utils/editable/utils/stringifyPipelineJson.d.ts +1 -1
  161. package/esm/typings/src/utils/environment/$getGlobalScope.d.ts +2 -1
  162. package/esm/typings/src/utils/expectation-counters/index.d.ts +1 -1
  163. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +2 -2
  164. package/esm/typings/src/utils/markdown/extractAllListItemsFromMarkdown.d.ts +1 -1
  165. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  166. package/esm/typings/src/utils/normalization/nameToUriPart.d.ts +4 -4
  167. package/esm/typings/src/utils/normalization/nameToUriParts.d.ts +4 -4
  168. package/esm/typings/src/utils/normalization/normalize-to-kebab-case.d.ts +3 -3
  169. package/esm/typings/src/utils/normalization/normalizeTo_SCREAMING_CASE.d.ts +3 -3
  170. package/esm/typings/src/utils/normalization/normalizeTo_camelCase.d.ts +4 -4
  171. package/esm/typings/src/utils/normalization/normalizeTo_snake_case.d.ts +3 -3
  172. package/esm/typings/src/utils/normalization/removeDiacritics.d.ts +3 -3
  173. package/esm/typings/src/utils/normalization/searchKeywords.d.ts +4 -1
  174. package/esm/typings/src/utils/normalization/titleToName.d.ts +4 -4
  175. package/esm/typings/src/utils/organization/TODO_USE.d.ts +1 -1
  176. package/esm/typings/src/utils/organization/empty_object.d.ts +2 -2
  177. package/esm/typings/src/utils/organization/just.d.ts +1 -1
  178. package/esm/typings/src/utils/organization/just_empty_object.d.ts +4 -4
  179. package/esm/typings/src/utils/organization/keepUnused.d.ts +1 -1
  180. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +7 -7
  181. package/esm/typings/src/utils/removeQuotes.d.ts +2 -2
  182. package/esm/typings/src/utils/serialization/clonePipeline.d.ts +4 -3
  183. package/esm/typings/src/utils/serialization/deepClone.d.ts +5 -1
  184. package/esm/typings/src/utils/trimCodeBlock.d.ts +1 -1
  185. package/esm/typings/src/utils/trimEndOfCodeBlock.d.ts +1 -1
  186. package/esm/typings/src/utils/unwrapResult.d.ts +2 -2
  187. package/esm/typings/src/utils/validators/javascriptName/isValidJavascriptName.d.ts +3 -3
  188. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +5 -4
  189. package/esm/typings/src/utils/validators/semanticVersion/isValidPromptbookVersion.d.ts +1 -1
  190. package/esm/typings/src/utils/validators/semanticVersion/isValidSemanticVersion.d.ts +1 -1
  191. package/esm/typings/src/utils/validators/url/isHostnameOnPrivateNetwork.d.ts +1 -1
  192. package/esm/typings/src/utils/validators/url/isUrlOnPrivateNetwork.d.ts +1 -1
  193. package/esm/typings/src/utils/validators/url/isValidPipelineUrl.d.ts +1 -1
  194. package/esm/typings/src/utils/validators/url/isValidUrl.d.ts +1 -1
  195. package/esm/typings/src/version.d.ts +2 -1
  196. package/esm/typings/src/wizzard/wizzard.d.ts +1 -1
  197. package/package.json +14 -2
  198. package/umd/index.umd.js +1037 -649
  199. package/umd/index.umd.js.map +1 -1
  200. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +0 -31
  201. package/esm/typings/src/formats/csv/CsvFormatDefinition.d.ts +0 -17
  202. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +0 -19
  203. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +0 -19
  204. /package/esm/typings/src/llm-providers/{multiple → _multiple}/MultipleLlmExecutionTools.d.ts +0 -0
  205. /package/esm/typings/src/llm-providers/{multiple → _multiple}/joinLlmExecutionTools.d.ts +0 -0
  206. /package/esm/typings/src/llm-providers/{multiple → _multiple}/playground/playground.d.ts +0 -0
package/esm/index.es.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
- import { Subject } from 'rxjs';
5
4
  import { randomBytes } from 'crypto';
5
+ import { Subject } from 'rxjs';
6
6
  import { forTime } from 'waitasecond';
7
7
  import { parse, unparse } from 'papaparse';
8
8
  import hexEncoder from 'crypto-js/enc-hex';
@@ -27,7 +27,7 @@ const BOOK_LANGUAGE_VERSION = '1.0.0';
27
27
  * @generated
28
28
  * @see https://github.com/webgptorg/promptbook
29
29
  */
30
- const PROMPTBOOK_ENGINE_VERSION = '0.92.0-9';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.93.0';
31
31
  /**
32
32
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
33
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -117,7 +117,7 @@ function isValidFilePath(filename) {
117
117
  * Tests if given string is valid URL.
118
118
  *
119
119
  * Note: Dataurl are considered perfectly valid.
120
- * Note: There are two simmilar functions:
120
+ * Note: There are two similar functions:
121
121
  * - `isValidUrl` which tests any URL
122
122
  * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
123
123
  *
@@ -193,7 +193,7 @@ const REMOTE_SERVER_URLS = [
193
193
  * Returns the same value that is passed as argument.
194
194
  * No side effects.
195
195
  *
196
- * Note: It can be usefull for:
196
+ * Note: It can be useful for:
197
197
  *
198
198
  * 1) Leveling indentation
199
199
  * 2) Putting always-true or always-false conditions without getting eslint errors
@@ -274,6 +274,28 @@ const DEFAULT_BOOK_OUTPUT_PARAMETER_NAME = 'result';
274
274
  * @public exported from `@promptbook/core`
275
275
  */
276
276
  const DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
277
+ /**
278
+ * Threshold value that determines when a dataset is considered "big"
279
+ * and may require special handling or optimizations
280
+ *
281
+ * For example, when error occurs in one item of the big dataset, it will not fail the whole pipeline
282
+ *
283
+ * @public exported from `@promptbook/core`
284
+ */
285
+ const BIG_DATASET_TRESHOLD = 50;
286
+ /**
287
+ * Placeholder text used to represent a placeholder value of failed operation
288
+ *
289
+ * @public exported from `@promptbook/core`
290
+ */
291
+ const FAILED_VALUE_PLACEHOLDER = '!?';
292
+ /**
293
+ * Placeholder text used to represent operations or values that are still in progress
294
+ * or awaiting completion in UI displays and logging
295
+ *
296
+ * @public exported from `@promptbook/core`
297
+ */
298
+ const PENDING_VALUE_PLACEHOLDER = '…';
277
299
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
278
300
  /**
279
301
  * The maximum number of iterations for a loops
@@ -334,19 +356,21 @@ const DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
334
356
  */
335
357
  const DEFAULT_MAX_EXECUTION_ATTEMPTS = 10; // <- TODO: [🤹‍♂️]
336
358
  /**
337
- * @@@
338
- * TODO: [🐝][main] !!3 Use
359
+ * The maximum depth to which knowledge sources will be scraped when building a knowledge base.
360
+ * This prevents infinite recursion and limits resource usage.
339
361
  *
340
362
  * @public exported from `@promptbook/core`
341
363
  */
342
364
  const DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = 3;
365
+ // <- TODO: [🐝]
343
366
  /**
344
- * @@@
345
- * TODO: [🐝][main] !!3 Use
367
+ * The maximum total number of knowledge sources that will be scraped in a single operation.
368
+ * This acts as a global limit to avoid excessive resource consumption.
346
369
  *
347
370
  * @public exported from `@promptbook/core`
348
371
  */
349
372
  const DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL = 200;
373
+ // <- TODO: [🐝]
350
374
  /**
351
375
  * Where to store your books
352
376
  * This is kind of a "src" for your books
@@ -424,7 +448,7 @@ const MOMENT_ARG_THRESHOLDS = {
424
448
  const DEFAULT_REMOTE_SERVER_URL = REMOTE_SERVER_URLS[0].urls[0];
425
449
  // <- TODO: [🧜‍♂️]
426
450
  /**
427
- * @@@
451
+ * Default settings for parsing and generating CSV files in Promptbook.
428
452
  *
429
453
  * @public exported from `@promptbook/core`
430
454
  */
@@ -435,15 +459,15 @@ const DEFAULT_CSV_SETTINGS = Object.freeze({
435
459
  skipEmptyLines: true,
436
460
  });
437
461
  /**
438
- * @@@
462
+ * Controls whether verbose logging is enabled by default throughout the application.
439
463
  *
440
464
  * @public exported from `@promptbook/core`
441
465
  */
442
466
  let DEFAULT_IS_VERBOSE = false;
443
467
  /**
444
- * @@@
468
+ * Enables or disables verbose logging globally at runtime.
445
469
  *
446
- * Note: This is experimental feature
470
+ * Note: This is an experimental feature.
447
471
  *
448
472
  * @public exported from `@promptbook/core`
449
473
  */
@@ -451,7 +475,7 @@ function SET_IS_VERBOSE(isVerbose) {
451
475
  DEFAULT_IS_VERBOSE = isVerbose;
452
476
  }
453
477
  /**
454
- * @@@
478
+ * Controls whether auto-installation of dependencies is enabled by default.
455
479
  *
456
480
  * @public exported from `@promptbook/core`
457
481
  */
@@ -463,7 +487,15 @@ const DEFAULT_IS_AUTO_INSTALLED = false;
463
487
  */
464
488
  const DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME = `getPipelineCollection`;
465
489
  /**
466
- * @@@
490
+ * Default rate limits (requests per minute)
491
+ *
492
+ * Note: Adjust based on the provider tier you are have
493
+ *
494
+ * @public exported from `@promptbook/core`
495
+ */
496
+ const DEFAULT_MAX_REQUESTS_PER_MINUTE = 60;
497
+ /**
498
+ * Indicates whether pipeline logic validation is enabled. When true, the pipeline logic is checked for consistency.
467
499
  *
468
500
  * @private within the repository
469
501
  */
@@ -531,7 +563,7 @@ class UnexpectedError extends Error {
531
563
  ${block(message)}
532
564
 
533
565
  Note: This error should not happen.
534
- It's probbably a bug in the pipeline collection
566
+ It's probably a bug in the pipeline collection
535
567
 
536
568
  Please report issue:
537
569
  ${block(getErrorReportUrl(new Error(message)).href)}
@@ -596,7 +628,7 @@ function assertsError(whatWasThrown) {
596
628
  * Function isValidJsonString will tell you if the string is valid JSON or not
597
629
  *
598
630
  * @param value The string to check
599
- * @returns True if the string is a valid JSON string, false otherwise
631
+ * @returns `true` if the string is a valid JSON string, false otherwise
600
632
  *
601
633
  * @public exported from `@promptbook/utils`
602
634
  */
@@ -708,7 +740,7 @@ function pipelineJsonToString(pipelineJson) {
708
740
  if (bookVersion !== `undefined`) {
709
741
  commands.push(`BOOK VERSION ${bookVersion}`);
710
742
  }
711
- // TODO: [main] !!5 This increases size of the bundle and is probbably not necessary
743
+ // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
712
744
  pipelineString = prettifyMarkdown(pipelineString);
713
745
  for (const parameter of parameters.filter(({ isInput }) => isInput)) {
714
746
  commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
@@ -1007,8 +1039,12 @@ function checkSerializableAsJson(options) {
1007
1039
  */
1008
1040
 
1009
1041
  /**
1010
- * @@@
1042
+ * Creates a deep clone of the given object
1043
+ *
1044
+ * Note: This method only works for objects that are fully serializable to JSON and do not contain functions, Dates, or special types.
1011
1045
  *
1046
+ * @param objectValue The object to clone.
1047
+ * @returns A deep, writable clone of the input object.
1012
1048
  * @public exported from `@promptbook/utils`
1013
1049
  */
1014
1050
  function deepClone(objectValue) {
@@ -1063,6 +1099,42 @@ function exportJson(options) {
1063
1099
  * TODO: [🧠] Is there a way how to meaningfully test this utility
1064
1100
  */
1065
1101
 
1102
+ /**
1103
+ * How is the model provider trusted?
1104
+ *
1105
+ * @public exported from `@promptbook/core`
1106
+ */
1107
+ const MODEL_TRUST_LEVELS = {
1108
+ FULL: `Model is running on the local machine, training data and model weights are known, data are ethically sourced`,
1109
+ OPEN: `Model is open source, training data and model weights are known`,
1110
+ PARTIALLY_OPEN: `Model is open source, but training data and model weights are not (fully) known`,
1111
+ CLOSED_LOCAL: `Model can be run locally, but it is not open source`,
1112
+ CLOSED_FREE: `Model is behind API gateway but free to use`,
1113
+ CLOSED_BUSINESS: `Model is behind API gateway and paid but has good SLA, TOS, privacy policy and in general is a good to use in business applications`,
1114
+ CLOSED: `Model is behind API gateway and paid`,
1115
+ UNTRUSTED: `Model has questions about the training data and ethics, but it is not known if it is a problem or not`,
1116
+ VURNABLE: `Model has some known serious vulnerabilities, leaks, ethical problems, etc.`,
1117
+ };
1118
+ // <- TODO: Maybe do better levels of trust
1119
+ /**
1120
+ * How is the model provider important?
1121
+ *
1122
+ * @public exported from `@promptbook/core`
1123
+ */
1124
+ const MODEL_ORDERS = {
1125
+ /**
1126
+ * Top-tier models, e.g. OpenAI, Anthropic,...
1127
+ */
1128
+ TOP_TIER: 333,
1129
+ /**
1130
+ * Mid-tier models, e.g. Llama, Mistral, etc.
1131
+ */
1132
+ NORMAL: 100,
1133
+ /**
1134
+ * Low-tier models, e.g. Phi, Tiny, etc.
1135
+ */
1136
+ LOW_TIER: 0,
1137
+ };
1066
1138
  /**
1067
1139
  * Order of keys in the pipeline JSON
1068
1140
  *
@@ -1090,13 +1162,13 @@ const ORDER_OF_PIPELINE_JSON = [
1090
1162
  */
1091
1163
  const REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
1092
1164
  /**
1093
- * @@@
1165
+ * Placeholder value indicating a parameter is missing its value.
1094
1166
  *
1095
1167
  * @private within the repository
1096
1168
  */
1097
1169
  const RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
1098
1170
  /**
1099
- * @@@
1171
+ * Placeholder value indicating a parameter is restricted and cannot be used directly.
1100
1172
  *
1101
1173
  * @private within the repository
1102
1174
  */
@@ -1141,7 +1213,7 @@ class PipelineLogicError extends Error {
1141
1213
  /**
1142
1214
  * Tests if given string is valid semantic version
1143
1215
  *
1144
- * Note: There are two simmilar functions:
1216
+ * Note: There are two similar functions:
1145
1217
  * - `isValidSemanticVersion` which tests any semantic version
1146
1218
  * - `isValidPromptbookVersion` *(this one)* which tests just Promptbook versions
1147
1219
  *
@@ -1163,7 +1235,7 @@ function isValidSemanticVersion(version) {
1163
1235
  *
1164
1236
  * @see https://www.npmjs.com/package/promptbook?activeTab=versions
1165
1237
  * Note: When you are using for example promptbook 2.0.0 and there already is promptbook 3.0.0 it don`t know about it.
1166
- * Note: There are two simmilar functions:
1238
+ * Note: There are two similar functions:
1167
1239
  * - `isValidSemanticVersion` which tests any semantic version
1168
1240
  * - `isValidPromptbookVersion` *(this one)* which tests just Promptbook versions
1169
1241
  *
@@ -1183,7 +1255,7 @@ function isValidPromptbookVersion(version) {
1183
1255
  /**
1184
1256
  * Tests if given string is valid pipeline URL URL.
1185
1257
  *
1186
- * Note: There are two simmilar functions:
1258
+ * Note: There are two similar functions:
1187
1259
  * - `isValidUrl` which tests any URL
1188
1260
  * - `isValidPipelineUrl` *(this one)* which tests just pipeline URL
1189
1261
  *
@@ -1280,7 +1352,7 @@ function validatePipeline_InnerFunction(pipeline) {
1280
1352
  ${block(pipelineIdentification)}
1281
1353
  `));
1282
1354
  }
1283
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1355
+ // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
1284
1356
  if (!Array.isArray(pipeline.parameters)) {
1285
1357
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1286
1358
  throw new ParseError(spaceTrim$1((block) => `
@@ -1291,7 +1363,7 @@ function validatePipeline_InnerFunction(pipeline) {
1291
1363
  ${block(pipelineIdentification)}
1292
1364
  `));
1293
1365
  }
1294
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1366
+ // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
1295
1367
  if (!Array.isArray(pipeline.tasks)) {
1296
1368
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1297
1369
  throw new ParseError(spaceTrim$1((block) => `
@@ -1595,7 +1667,7 @@ class SimplePipelineCollection {
1595
1667
  /**
1596
1668
  * Constructs a pipeline collection from pipelines
1597
1669
  *
1598
- * @param pipelines @@@
1670
+ * @param pipelines Array of pipeline JSON objects to include in the collection
1599
1671
  *
1600
1672
  * Note: During the construction logic of all pipelines are validated
1601
1673
  * Note: It is not recommended to use this constructor directly, use `createCollectionFromJson` *(or other variant)* instead
@@ -1833,7 +1905,7 @@ class MissingToolsError extends Error {
1833
1905
  super(spaceTrim$1((block) => `
1834
1906
  ${block(message)}
1835
1907
 
1836
- Note: You have probbably forgot to provide some tools for pipeline execution or preparation
1908
+ Note: You have probably forgot to provide some tools for pipeline execution or preparation
1837
1909
 
1838
1910
  `));
1839
1911
  this.name = 'MissingToolsError';
@@ -1849,15 +1921,18 @@ class MissingToolsError extends Error {
1849
1921
  * @public exported from `@promptbook/core`
1850
1922
  */
1851
1923
  function isPipelinePrepared(pipeline) {
1852
- // Note: Ignoring `pipeline.preparations` @@@
1853
- // Note: Ignoring `pipeline.knowledgePieces` @@@
1924
+ // Note: Ignoring `pipeline.preparations`
1925
+ // Note: Ignoring `pipeline.knowledgePieces`
1854
1926
  if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1927
+ // console.log('Pipeline is not prepared because title is undefined or empty', pipeline);
1855
1928
  return false;
1856
1929
  }
1857
1930
  if (!pipeline.personas.every((persona) => persona.modelsRequirements !== undefined)) {
1931
+ // console.log('Pipeline is not prepared because personas are not prepared', pipeline.personas);
1858
1932
  return false;
1859
1933
  }
1860
1934
  if (!pipeline.knowledgeSources.every((knowledgeSource) => knowledgeSource.preparationIds !== undefined)) {
1935
+ //console.log('Pipeline is not prepared because knowledge sources are not prepared', pipeline.knowledgeSources);
1861
1936
  return false;
1862
1937
  }
1863
1938
  /*
@@ -1878,109 +1953,6 @@ function isPipelinePrepared(pipeline) {
1878
1953
  * - [♨] Are tasks prepared
1879
1954
  */
1880
1955
 
1881
- /**
1882
- * Generates random token
1883
- *
1884
- * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
1885
- *
1886
- * @private internal helper function
1887
- * @returns secure random token
1888
- */
1889
- function $randomToken(randomness) {
1890
- return randomBytes(randomness).toString('hex');
1891
- }
1892
- /**
1893
- * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
1894
- */
1895
-
1896
- /**
1897
- * Converts a JavaScript Object Notation (JSON) string into an object.
1898
- *
1899
- * Note: This is wrapper around `JSON.parse()` with better error and type handling
1900
- *
1901
- * @public exported from `@promptbook/utils`
1902
- */
1903
- function jsonParse(value) {
1904
- if (value === undefined) {
1905
- throw new Error(`Can not parse JSON from undefined value.`);
1906
- }
1907
- else if (typeof value !== 'string') {
1908
- console.error('Can not parse JSON from non-string value.', { text: value });
1909
- throw new Error(spaceTrim(`
1910
- Can not parse JSON from non-string value.
1911
-
1912
- The value type: ${typeof value}
1913
- See more in console.
1914
- `));
1915
- }
1916
- try {
1917
- return JSON.parse(value);
1918
- }
1919
- catch (error) {
1920
- if (!(error instanceof Error)) {
1921
- throw error;
1922
- }
1923
- throw new Error(spaceTrim((block) => `
1924
- ${block(error.message)}
1925
-
1926
- The JSON text:
1927
- ${block(value)}
1928
- `));
1929
- }
1930
- }
1931
- /**
1932
- * TODO: !!!! Use in Promptbook.studio
1933
- */
1934
-
1935
- /**
1936
- * Recursively converts JSON strings to JSON objects
1937
-
1938
- * @public exported from `@promptbook/utils`
1939
- */
1940
- function jsonStringsToJsons(object) {
1941
- if (object === null) {
1942
- return object;
1943
- }
1944
- if (Array.isArray(object)) {
1945
- return object.map(jsonStringsToJsons);
1946
- }
1947
- if (typeof object !== 'object') {
1948
- return object;
1949
- }
1950
- const newObject = { ...object };
1951
- for (const [key, value] of Object.entries(object)) {
1952
- if (typeof value === 'string' && isValidJsonString(value)) {
1953
- newObject[key] = jsonParse(value);
1954
- }
1955
- else {
1956
- newObject[key] = jsonStringsToJsons(value);
1957
- }
1958
- }
1959
- return newObject;
1960
- }
1961
- /**
1962
- * TODO: Type the return type correctly
1963
- */
1964
-
1965
- /**
1966
- * This error indicates errors during the execution of the pipeline
1967
- *
1968
- * @public exported from `@promptbook/core`
1969
- */
1970
- class PipelineExecutionError extends Error {
1971
- constructor(message) {
1972
- // Added id parameter
1973
- super(message);
1974
- this.name = 'PipelineExecutionError';
1975
- // TODO: [🐙] DRY - Maybe $randomId
1976
- this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid simmilar char conflicts */)}`;
1977
- Object.setPrototypeOf(this, PipelineExecutionError.prototype);
1978
- }
1979
- }
1980
- /**
1981
- * TODO: [🧠][🌂] Add id to all errors
1982
- */
1983
-
1984
1956
  /**
1985
1957
  * This error indicates problems parsing the format value
1986
1958
  *
@@ -2025,7 +1997,7 @@ class AuthenticationError extends Error {
2025
1997
  }
2026
1998
 
2027
1999
  /**
2028
- * This error indicates that the pipeline collection cannot be propperly loaded
2000
+ * This error indicates that the pipeline collection cannot be properly loaded
2029
2001
  *
2030
2002
  * @public exported from `@promptbook/core`
2031
2003
  */
@@ -2115,6 +2087,40 @@ class NotYetImplementedError extends Error {
2115
2087
  }
2116
2088
  }
2117
2089
 
2090
+ /**
2091
+ * Generates random token
2092
+ *
2093
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
2094
+ *
2095
+ * @private internal helper function
2096
+ * @returns secure random token
2097
+ */
2098
+ function $randomToken(randomness) {
2099
+ return randomBytes(randomness).toString('hex');
2100
+ }
2101
+ /**
2102
+ * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
2103
+ */
2104
+
2105
+ /**
2106
+ * This error indicates errors during the execution of the pipeline
2107
+ *
2108
+ * @public exported from `@promptbook/core`
2109
+ */
2110
+ class PipelineExecutionError extends Error {
2111
+ constructor(message) {
2112
+ // Added id parameter
2113
+ super(message);
2114
+ this.name = 'PipelineExecutionError';
2115
+ // TODO: [🐙] DRY - Maybe $randomId
2116
+ this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
2117
+ Object.setPrototypeOf(this, PipelineExecutionError.prototype);
2118
+ }
2119
+ }
2120
+ /**
2121
+ * TODO: [🧠][🌂] Add id to all errors
2122
+ */
2123
+
2118
2124
  /**
2119
2125
  * Error thrown when a fetch request fails
2120
2126
  *
@@ -2190,6 +2196,101 @@ const ALL_ERRORS = {
2190
2196
  * Note: [💞] Ignore a discrepancy between file name and entity name
2191
2197
  */
2192
2198
 
2199
+ /**
2200
+ * Serializes an error into a [🚉] JSON-serializable object
2201
+ *
2202
+ * @public exported from `@promptbook/utils`
2203
+ */
2204
+ function serializeError(error) {
2205
+ const { name, message, stack } = error;
2206
+ const { id } = error;
2207
+ if (!Object.keys(ALL_ERRORS).includes(name)) {
2208
+ console.error(spaceTrim((block) => `
2209
+
2210
+ Cannot serialize error with name "${name}"
2211
+
2212
+ Authors of Promptbook probably forgot to add this error into the list of errors:
2213
+ https://github.com/webgptorg/promptbook/blob/main/src/errors/0-index.ts
2214
+
2215
+
2216
+ ${block(stack || message)}
2217
+
2218
+ `));
2219
+ }
2220
+ return {
2221
+ name: name,
2222
+ message,
2223
+ stack,
2224
+ id, // Include id in the serialized object
2225
+ };
2226
+ }
2227
+
2228
+ /**
2229
+ * Converts a JavaScript Object Notation (JSON) string into an object.
2230
+ *
2231
+ * Note: This is wrapper around `JSON.parse()` with better error and type handling
2232
+ *
2233
+ * @public exported from `@promptbook/utils`
2234
+ */
2235
+ function jsonParse(value) {
2236
+ if (value === undefined) {
2237
+ throw new Error(`Can not parse JSON from undefined value.`);
2238
+ }
2239
+ else if (typeof value !== 'string') {
2240
+ console.error('Can not parse JSON from non-string value.', { text: value });
2241
+ throw new Error(spaceTrim(`
2242
+ Can not parse JSON from non-string value.
2243
+
2244
+ The value type: ${typeof value}
2245
+ See more in console.
2246
+ `));
2247
+ }
2248
+ try {
2249
+ return JSON.parse(value);
2250
+ }
2251
+ catch (error) {
2252
+ if (!(error instanceof Error)) {
2253
+ throw error;
2254
+ }
2255
+ throw new Error(spaceTrim((block) => `
2256
+ ${block(error.message)}
2257
+
2258
+ The JSON text:
2259
+ ${block(value)}
2260
+ `));
2261
+ }
2262
+ }
2263
+
2264
+ /**
2265
+ * Recursively converts JSON strings to JSON objects
2266
+
2267
+ * @public exported from `@promptbook/utils`
2268
+ */
2269
+ function jsonStringsToJsons(object) {
2270
+ if (object === null) {
2271
+ return object;
2272
+ }
2273
+ if (Array.isArray(object)) {
2274
+ return object.map(jsonStringsToJsons);
2275
+ }
2276
+ if (typeof object !== 'object') {
2277
+ return object;
2278
+ }
2279
+ const newObject = { ...object };
2280
+ for (const [key, value] of Object.entries(object)) {
2281
+ if (typeof value === 'string' && isValidJsonString(value)) {
2282
+ newObject[key] = jsonParse(value);
2283
+ }
2284
+ else {
2285
+ newObject[key] = jsonStringsToJsons(value);
2286
+ }
2287
+ }
2288
+ return newObject;
2289
+ }
2290
+ /**
2291
+ * TODO: Type the return type correctly
2292
+ */
2293
+
2193
2294
  /**
2194
2295
  * Deserializes the error object
2195
2296
  *
@@ -2264,8 +2365,9 @@ function assertsTaskSuccessful(executionResult) {
2264
2365
  */
2265
2366
  function createTask(options) {
2266
2367
  const { taskType, taskProcessCallback } = options;
2368
+ let { title } = options;
2267
2369
  // TODO: [🐙] DRY
2268
- const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid simmilar char conflicts */)}`;
2370
+ const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
2269
2371
  let status = 'RUNNING';
2270
2372
  const createdAt = new Date();
2271
2373
  let updatedAt = createdAt;
@@ -2275,6 +2377,10 @@ function createTask(options) {
2275
2377
  const partialResultSubject = new Subject();
2276
2378
  // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
2277
2379
  const finalResultPromise = /* not await */ taskProcessCallback((newOngoingResult) => {
2380
+ if (newOngoingResult.title) {
2381
+ title = newOngoingResult.title;
2382
+ }
2383
+ updatedAt = new Date();
2278
2384
  Object.assign(currentValue, newOngoingResult);
2279
2385
  // <- TODO: assign deep
2280
2386
  partialResultSubject.next(newOngoingResult);
@@ -2320,17 +2426,24 @@ function createTask(options) {
2320
2426
  return {
2321
2427
  taskType,
2322
2428
  taskId,
2429
+ get promptbookVersion() {
2430
+ return PROMPTBOOK_ENGINE_VERSION;
2431
+ },
2432
+ get title() {
2433
+ return title;
2434
+ // <- Note: [1] These must be getters to allow changing the value in the future
2435
+ },
2323
2436
  get status() {
2324
2437
  return status;
2325
- // <- Note: [1] Theese must be getters to allow changing the value in the future
2438
+ // <- Note: [1] --||--
2326
2439
  },
2327
2440
  get createdAt() {
2328
2441
  return createdAt;
2329
- // <- Note: [1]
2442
+ // <- Note: [1] --||--
2330
2443
  },
2331
2444
  get updatedAt() {
2332
2445
  return updatedAt;
2333
- // <- Note: [1]
2446
+ // <- Note: [1] --||--
2334
2447
  },
2335
2448
  asPromise,
2336
2449
  asObservable() {
@@ -2338,15 +2451,15 @@ function createTask(options) {
2338
2451
  },
2339
2452
  get errors() {
2340
2453
  return errors;
2341
- // <- Note: [1]
2454
+ // <- Note: [1] --||--
2342
2455
  },
2343
2456
  get warnings() {
2344
2457
  return warnings;
2345
- // <- Note: [1]
2458
+ // <- Note: [1] --||--
2346
2459
  },
2347
2460
  get currentValue() {
2348
2461
  return currentValue;
2349
- // <- Note: [1]
2462
+ // <- Note: [1] --||--
2350
2463
  },
2351
2464
  };
2352
2465
  }
@@ -2356,33 +2469,72 @@ function createTask(options) {
2356
2469
  */
2357
2470
 
2358
2471
  /**
2359
- * Serializes an error into a [🚉] JSON-serializable object
2472
+ * Represents the uncertain value
2360
2473
  *
2361
- * @public exported from `@promptbook/utils`
2474
+ * @public exported from `@promptbook/core`
2475
+ */
2476
+ const ZERO_VALUE = $deepFreeze({ value: 0 });
2477
+ /**
2478
+ * Represents the uncertain value
2479
+ *
2480
+ * @public exported from `@promptbook/core`
2481
+ */
2482
+ const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
2483
+ /**
2484
+ * Represents the usage with no resources consumed
2485
+ *
2486
+ * @public exported from `@promptbook/core`
2487
+ */
2488
+ const ZERO_USAGE = $deepFreeze({
2489
+ price: ZERO_VALUE,
2490
+ input: {
2491
+ tokensCount: ZERO_VALUE,
2492
+ charactersCount: ZERO_VALUE,
2493
+ wordsCount: ZERO_VALUE,
2494
+ sentencesCount: ZERO_VALUE,
2495
+ linesCount: ZERO_VALUE,
2496
+ paragraphsCount: ZERO_VALUE,
2497
+ pagesCount: ZERO_VALUE,
2498
+ },
2499
+ output: {
2500
+ tokensCount: ZERO_VALUE,
2501
+ charactersCount: ZERO_VALUE,
2502
+ wordsCount: ZERO_VALUE,
2503
+ sentencesCount: ZERO_VALUE,
2504
+ linesCount: ZERO_VALUE,
2505
+ paragraphsCount: ZERO_VALUE,
2506
+ pagesCount: ZERO_VALUE,
2507
+ },
2508
+ });
2509
+ /**
2510
+ * Represents the usage with unknown resources consumed
2511
+ *
2512
+ * @public exported from `@promptbook/core`
2513
+ */
2514
+ const UNCERTAIN_USAGE = $deepFreeze({
2515
+ price: UNCERTAIN_ZERO_VALUE,
2516
+ input: {
2517
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2518
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2519
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2520
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2521
+ linesCount: UNCERTAIN_ZERO_VALUE,
2522
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2523
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2524
+ },
2525
+ output: {
2526
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2527
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2528
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2529
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2530
+ linesCount: UNCERTAIN_ZERO_VALUE,
2531
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2532
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2533
+ },
2534
+ });
2535
+ /**
2536
+ * Note: [💞] Ignore a discrepancy between file name and entity name
2362
2537
  */
2363
- function serializeError(error) {
2364
- const { name, message, stack } = error;
2365
- const { id } = error;
2366
- if (!Object.keys(ALL_ERRORS).includes(name)) {
2367
- console.error(spaceTrim((block) => `
2368
-
2369
- Cannot serialize error with name "${name}"
2370
-
2371
- Authors of Promptbook probably forgot to add this error into the list of errors:
2372
- https://github.com/webgptorg/promptbook/blob/main/src/errors/0-index.ts
2373
-
2374
-
2375
- ${block(stack || message)}
2376
-
2377
- `));
2378
- }
2379
- return {
2380
- name: name,
2381
- message,
2382
- stack,
2383
- id, // Include id in the serialized object
2384
- };
2385
- }
2386
2538
 
2387
2539
  /**
2388
2540
  * Format either small or big number
@@ -2465,74 +2617,6 @@ function valueToString(value) {
2465
2617
  }
2466
2618
  }
2467
2619
 
2468
- /**
2469
- * Represents the uncertain value
2470
- *
2471
- * @public exported from `@promptbook/core`
2472
- */
2473
- const ZERO_VALUE = $deepFreeze({ value: 0 });
2474
- /**
2475
- * Represents the uncertain value
2476
- *
2477
- * @public exported from `@promptbook/core`
2478
- */
2479
- const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
2480
- /**
2481
- * Represents the usage with no resources consumed
2482
- *
2483
- * @public exported from `@promptbook/core`
2484
- */
2485
- const ZERO_USAGE = $deepFreeze({
2486
- price: ZERO_VALUE,
2487
- input: {
2488
- tokensCount: ZERO_VALUE,
2489
- charactersCount: ZERO_VALUE,
2490
- wordsCount: ZERO_VALUE,
2491
- sentencesCount: ZERO_VALUE,
2492
- linesCount: ZERO_VALUE,
2493
- paragraphsCount: ZERO_VALUE,
2494
- pagesCount: ZERO_VALUE,
2495
- },
2496
- output: {
2497
- tokensCount: ZERO_VALUE,
2498
- charactersCount: ZERO_VALUE,
2499
- wordsCount: ZERO_VALUE,
2500
- sentencesCount: ZERO_VALUE,
2501
- linesCount: ZERO_VALUE,
2502
- paragraphsCount: ZERO_VALUE,
2503
- pagesCount: ZERO_VALUE,
2504
- },
2505
- });
2506
- /**
2507
- * Represents the usage with unknown resources consumed
2508
- *
2509
- * @public exported from `@promptbook/core`
2510
- */
2511
- const UNCERTAIN_USAGE = $deepFreeze({
2512
- price: UNCERTAIN_ZERO_VALUE,
2513
- input: {
2514
- tokensCount: UNCERTAIN_ZERO_VALUE,
2515
- charactersCount: UNCERTAIN_ZERO_VALUE,
2516
- wordsCount: UNCERTAIN_ZERO_VALUE,
2517
- sentencesCount: UNCERTAIN_ZERO_VALUE,
2518
- linesCount: UNCERTAIN_ZERO_VALUE,
2519
- paragraphsCount: UNCERTAIN_ZERO_VALUE,
2520
- pagesCount: UNCERTAIN_ZERO_VALUE,
2521
- },
2522
- output: {
2523
- tokensCount: UNCERTAIN_ZERO_VALUE,
2524
- charactersCount: UNCERTAIN_ZERO_VALUE,
2525
- wordsCount: UNCERTAIN_ZERO_VALUE,
2526
- sentencesCount: UNCERTAIN_ZERO_VALUE,
2527
- linesCount: UNCERTAIN_ZERO_VALUE,
2528
- paragraphsCount: UNCERTAIN_ZERO_VALUE,
2529
- pagesCount: UNCERTAIN_ZERO_VALUE,
2530
- },
2531
- });
2532
- /**
2533
- * Note: [💞] Ignore a discrepancy between file name and entity name
2534
- */
2535
-
2536
2620
  /**
2537
2621
  * Function `addUsage` will add multiple usages into one
2538
2622
  *
@@ -2741,7 +2825,7 @@ function union(...sets) {
2741
2825
  }
2742
2826
 
2743
2827
  /**
2744
- * @@@
2828
+ * Contains configuration options for parsing and generating CSV files, such as delimiters and quoting rules.
2745
2829
  *
2746
2830
  * @public exported from `@promptbook/core`
2747
2831
  */
@@ -2750,11 +2834,29 @@ const MANDATORY_CSV_SETTINGS = Object.freeze({
2750
2834
  // encoding: 'utf-8',
2751
2835
  });
2752
2836
 
2837
+ /**
2838
+ * Converts a CSV string into an object
2839
+ *
2840
+ * Note: This is wrapper around `papaparse.parse()` with better autohealing
2841
+ *
2842
+ * @private - for now until `@promptbook/csv` is released
2843
+ */
2844
+ function csvParse(value /* <- TODO: string_csv */, settings, schema /* <- TODO: Make CSV Schemas */) {
2845
+ settings = { ...settings, ...MANDATORY_CSV_SETTINGS };
2846
+ // Note: Autoheal invalid '\n' characters
2847
+ if (settings.newline && !settings.newline.includes('\r') && value.includes('\r')) {
2848
+ console.warn('CSV string contains carriage return characters, but in the CSV settings the `newline` setting does not include them. Autohealing the CSV string.');
2849
+ value = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
2850
+ }
2851
+ const csv = parse(value, settings);
2852
+ return csv;
2853
+ }
2854
+
2753
2855
  /**
2754
2856
  * Function to check if a string is valid CSV
2755
2857
  *
2756
2858
  * @param value The string to check
2757
- * @returns True if the string is a valid CSV string, false otherwise
2859
+ * @returns `true` if the string is a valid CSV string, false otherwise
2758
2860
  *
2759
2861
  * @public exported from `@promptbook/utils`
2760
2862
  */
@@ -2778,7 +2880,7 @@ function isValidCsvString(value) {
2778
2880
  * @public exported from `@promptbook/core`
2779
2881
  * <- TODO: [🏢] Export from package `@promptbook/csv`
2780
2882
  */
2781
- const CsvFormatDefinition = {
2883
+ const CsvFormatParser = {
2782
2884
  formatName: 'CSV',
2783
2885
  aliases: ['SPREADSHEET', 'TABLE'],
2784
2886
  isValid(value, settings, schema) {
@@ -2790,12 +2892,12 @@ const CsvFormatDefinition = {
2790
2892
  heal(value, settings, schema) {
2791
2893
  throw new Error('Not implemented');
2792
2894
  },
2793
- subvalueDefinitions: [
2895
+ subvalueParsers: [
2794
2896
  {
2795
2897
  subvalueName: 'ROW',
2796
- async mapValues(value, outputParameterName, settings, mapCallback) {
2797
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
2798
- const csv = parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
2898
+ async mapValues(options) {
2899
+ const { value, outputParameterName, settings, mapCallback, onProgress } = options;
2900
+ const csv = csvParse(value, settings);
2799
2901
  if (csv.errors.length !== 0) {
2800
2902
  throw new CsvFormatError(spaceTrim((block) => `
2801
2903
  CSV parsing error
@@ -2810,23 +2912,37 @@ const CsvFormatDefinition = {
2810
2912
  ${block(value)}
2811
2913
  `));
2812
2914
  }
2813
- const mappedData = await Promise.all(csv.data.map(async (row, index) => {
2915
+ const mappedData = [];
2916
+ const length = csv.data.length;
2917
+ for (let index = 0; index < length; index++) {
2918
+ const row = csv.data[index];
2814
2919
  if (row[outputParameterName]) {
2815
2920
  throw new CsvFormatError(`Can not overwrite existing column "${outputParameterName}" in CSV row`);
2816
2921
  }
2817
- return {
2922
+ const mappedRow = {
2818
2923
  ...row,
2819
- [outputParameterName]: await mapCallback(row, index),
2924
+ [outputParameterName]: await mapCallback(row, index, length),
2820
2925
  };
2821
- }));
2926
+ mappedData.push(mappedRow);
2927
+ if (onProgress) {
2928
+ // Note: Report the CSV with all rows mapped so far
2929
+ /*
2930
+ // TODO: [🛕] Report progress with all the rows including the pending ones
2931
+ const progressData = mappedData.map((row, i) =>
2932
+ i > index ? { ...row, [outputParameterName]: PENDING_VALUE_PLACEHOLDER } : row,
2933
+ );
2934
+ */
2935
+ await onProgress(unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS }));
2936
+ }
2937
+ }
2822
2938
  return unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS });
2823
2939
  },
2824
2940
  },
2825
2941
  {
2826
2942
  subvalueName: 'CELL',
2827
- async mapValues(value, outputParameterName, settings, mapCallback) {
2828
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
2829
- const csv = parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
2943
+ async mapValues(options) {
2944
+ const { value, settings, mapCallback, onProgress } = options;
2945
+ const csv = csvParse(value, settings);
2830
2946
  if (csv.errors.length !== 0) {
2831
2947
  throw new CsvFormatError(spaceTrim((block) => `
2832
2948
  CSV parsing error
@@ -2842,9 +2958,9 @@ const CsvFormatDefinition = {
2842
2958
  `));
2843
2959
  }
2844
2960
  const mappedData = await Promise.all(csv.data.map(async (row, rowIndex) => {
2845
- return /* not await */ Promise.all(Object.entries(row).map(async ([key, value], columnIndex) => {
2961
+ return /* not await */ Promise.all(Object.entries(row).map(async ([key, value], columnIndex, array) => {
2846
2962
  const index = rowIndex * Object.keys(row).length + columnIndex;
2847
- return /* not await */ mapCallback({ [key]: value }, index);
2963
+ return /* not await */ mapCallback({ [key]: value }, index, array.length);
2848
2964
  }));
2849
2965
  }));
2850
2966
  return unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS });
@@ -2853,10 +2969,10 @@ const CsvFormatDefinition = {
2853
2969
  ],
2854
2970
  };
2855
2971
  /**
2856
- * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2857
- * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2858
- * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2859
- * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2972
+ * TODO: [🍓] In `CsvFormatParser` implement simple `isValid`
2973
+ * TODO: [🍓] In `CsvFormatParser` implement partial `canBeValid`
2974
+ * TODO: [🍓] In `CsvFormatParser` implement `heal
2975
+ * TODO: [🍓] In `CsvFormatParser` implement `subvalueParsers`
2860
2976
  * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2861
2977
  */
2862
2978
 
@@ -2865,7 +2981,7 @@ const CsvFormatDefinition = {
2865
2981
  *
2866
2982
  * @private still in development [🏢]
2867
2983
  */
2868
- const JsonFormatDefinition = {
2984
+ const JsonFormatParser = {
2869
2985
  formatName: 'JSON',
2870
2986
  mimeType: 'application/json',
2871
2987
  isValid(value, settings, schema) {
@@ -2877,28 +2993,28 @@ const JsonFormatDefinition = {
2877
2993
  heal(value, settings, schema) {
2878
2994
  throw new Error('Not implemented');
2879
2995
  },
2880
- subvalueDefinitions: [],
2996
+ subvalueParsers: [],
2881
2997
  };
2882
2998
  /**
2883
- * TODO: [🧠] Maybe propper instance of object
2999
+ * TODO: [🧠] Maybe proper instance of object
2884
3000
  * TODO: [0] Make string_serialized_json
2885
3001
  * TODO: [1] Make type for JSON Settings and Schema
2886
3002
  * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2887
- * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2888
- * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2889
- * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2890
- * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3003
+ * TODO: [🍓] In `JsonFormatParser` implement simple `isValid`
3004
+ * TODO: [🍓] In `JsonFormatParser` implement partial `canBeValid`
3005
+ * TODO: [🍓] In `JsonFormatParser` implement `heal
3006
+ * TODO: [🍓] In `JsonFormatParser` implement `subvalueParsers`
2891
3007
  * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2892
3008
  */
2893
3009
 
2894
3010
  /**
2895
3011
  * Definition for any text - this will be always valid
2896
3012
  *
2897
- * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3013
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueParsers`
2898
3014
  *
2899
3015
  * @public exported from `@promptbook/core`
2900
3016
  */
2901
- const TextFormatDefinition = {
3017
+ const TextFormatParser = {
2902
3018
  formatName: 'TEXT',
2903
3019
  isValid(value) {
2904
3020
  return typeof value === 'string';
@@ -2907,19 +3023,20 @@ const TextFormatDefinition = {
2907
3023
  return typeof partialValue === 'string';
2908
3024
  },
2909
3025
  heal() {
2910
- throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3026
+ throw new UnexpectedError('It does not make sense to call `TextFormatParser.heal`');
2911
3027
  },
2912
- subvalueDefinitions: [
3028
+ subvalueParsers: [
2913
3029
  {
2914
3030
  subvalueName: 'LINE',
2915
- async mapValues(value, outputParameterName, settings, mapCallback) {
3031
+ async mapValues(options) {
3032
+ const { value, mapCallback, onProgress } = options;
2916
3033
  const lines = value.split('\n');
2917
- const mappedLines = await Promise.all(lines.map((lineContent, lineNumber) =>
3034
+ const mappedLines = await Promise.all(lines.map((lineContent, lineNumber, array) =>
2918
3035
  // TODO: [🧠] Maybe option to skip empty line
2919
3036
  /* not await */ mapCallback({
2920
3037
  lineContent,
2921
3038
  // TODO: [🧠] Maybe also put here `lineNumber`
2922
- }, lineNumber)));
3039
+ }, lineNumber, array.length)));
2923
3040
  return mappedLines.join('\n');
2924
3041
  },
2925
3042
  },
@@ -2929,10 +3046,10 @@ const TextFormatDefinition = {
2929
3046
  /**
2930
3047
  * TODO: [1] Make type for XML Text and Schema
2931
3048
  * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages available as subvalues
2932
- * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
2933
- * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
2934
- * TODO: [🍓] In `TextFormatDefinition` implement `heal
2935
- * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3049
+ * TODO: [🍓] In `TextFormatParser` implement simple `isValid`
3050
+ * TODO: [🍓] In `TextFormatParser` implement partial `canBeValid`
3051
+ * TODO: [🍓] In `TextFormatParser` implement `heal
3052
+ * TODO: [🍓] In `TextFormatParser` implement `subvalueParsers`
2936
3053
  * TODO: [🏢] Allow to expect something inside each item of list and other formats
2937
3054
  */
2938
3055
 
@@ -2940,7 +3057,7 @@ const TextFormatDefinition = {
2940
3057
  * Function to check if a string is valid XML
2941
3058
  *
2942
3059
  * @param value
2943
- * @returns True if the string is a valid XML string, false otherwise
3060
+ * @returns `true` if the string is a valid XML string, false otherwise
2944
3061
  *
2945
3062
  * @public exported from `@promptbook/utils`
2946
3063
  */
@@ -2965,7 +3082,7 @@ function isValidXmlString(value) {
2965
3082
  *
2966
3083
  * @private still in development [🏢]
2967
3084
  */
2968
- const XmlFormatDefinition = {
3085
+ const XmlFormatParser = {
2969
3086
  formatName: 'XML',
2970
3087
  mimeType: 'application/xml',
2971
3088
  isValid(value, settings, schema) {
@@ -2977,17 +3094,17 @@ const XmlFormatDefinition = {
2977
3094
  heal(value, settings, schema) {
2978
3095
  throw new Error('Not implemented');
2979
3096
  },
2980
- subvalueDefinitions: [],
3097
+ subvalueParsers: [],
2981
3098
  };
2982
3099
  /**
2983
- * TODO: [🧠] Maybe propper instance of object
3100
+ * TODO: [🧠] Maybe proper instance of object
2984
3101
  * TODO: [0] Make string_serialized_xml
2985
3102
  * TODO: [1] Make type for XML Settings and Schema
2986
3103
  * TODO: [🧠] What to use for validating XMLs - XSD,...
2987
- * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
2988
- * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
2989
- * TODO: [🍓] In `XmlFormatDefinition` implement `heal
2990
- * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3104
+ * TODO: [🍓] In `XmlFormatParser` implement simple `isValid`
3105
+ * TODO: [🍓] In `XmlFormatParser` implement partial `canBeValid`
3106
+ * TODO: [🍓] In `XmlFormatParser` implement `heal
3107
+ * TODO: [🍓] In `XmlFormatParser` implement `subvalueParsers`
2991
3108
  * TODO: [🏢] Allow to expect something inside XML and other formats
2992
3109
  */
2993
3110
 
@@ -2996,24 +3113,19 @@ const XmlFormatDefinition = {
2996
3113
  *
2997
3114
  * @private internal index of `...` <- TODO [🏢]
2998
3115
  */
2999
- const FORMAT_DEFINITIONS = [
3000
- JsonFormatDefinition,
3001
- XmlFormatDefinition,
3002
- TextFormatDefinition,
3003
- CsvFormatDefinition,
3004
- ];
3116
+ const FORMAT_DEFINITIONS = [JsonFormatParser, XmlFormatParser, TextFormatParser, CsvFormatParser];
3005
3117
  /**
3006
3118
  * Note: [💞] Ignore a discrepancy between file name and entity name
3007
3119
  */
3008
3120
 
3009
3121
  /**
3010
- * Maps available parameters to expected parameters
3122
+ * Maps available parameters to expected parameters for a pipeline task.
3011
3123
  *
3012
3124
  * The strategy is:
3013
- * 1) @@@
3014
- * 2) @@@
3125
+ * 1) First, match parameters by name where both available and expected.
3126
+ * 2) Then, if there are unmatched expected and available parameters, map them by order.
3015
3127
  *
3016
- * @throws {PipelineExecutionError} @@@
3128
+ * @throws {PipelineExecutionError} If the number of unmatched expected and available parameters does not match, or mapping is ambiguous.
3017
3129
  * @private within the repository used in `createPipelineExecutor`
3018
3130
  */
3019
3131
  function mapAvailableToExpectedParameters(options) {
@@ -3036,7 +3148,7 @@ function mapAvailableToExpectedParameters(options) {
3036
3148
  else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) ;
3037
3149
  }
3038
3150
  if (expectedParameterNames.size === 0) {
3039
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3151
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent accidental modifications after mapping
3040
3152
  Object.freeze(mappedParameters);
3041
3153
  return mappedParameters;
3042
3154
  }
@@ -3067,7 +3179,7 @@ function mapAvailableToExpectedParameters(options) {
3067
3179
  for (let i = 0; i < expectedParameterNames.size; i++) {
3068
3180
  mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3069
3181
  }
3070
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3182
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent accidental modifications after mapping
3071
3183
  Object.freeze(mappedParameters);
3072
3184
  return mappedParameters;
3073
3185
  }
@@ -3089,29 +3201,40 @@ class MultipleLlmExecutionTools {
3089
3201
  return 'Multiple LLM Providers';
3090
3202
  }
3091
3203
  get description() {
3092
- return this.llmExecutionTools.map(({ title }, index) => `${index + 1}) \`${title}\``).join('\n');
3204
+ const innerModelsTitlesAndDescriptions = this.llmExecutionTools
3205
+ .map(({ title, description }, index) => {
3206
+ const headLine = `${index + 1}) \`${title}\``;
3207
+ if (description === undefined) {
3208
+ return headLine;
3209
+ }
3210
+ return spaceTrim((block) => `
3211
+ ${headLine}
3212
+
3213
+ ${ /* <- Note: Indenting the description: */block(description)}
3214
+ `);
3215
+ })
3216
+ .join('\n\n');
3217
+ return spaceTrim((block) => `
3218
+ Multiple LLM Providers:
3219
+
3220
+ ${block(innerModelsTitlesAndDescriptions)}
3221
+ `);
3093
3222
  }
3094
3223
  /**
3095
3224
  * Check the configuration of all execution tools
3096
3225
  */
3097
3226
  async checkConfiguration() {
3098
- // TODO: Maybe do it in parallel
3099
- for (const llmExecutionTools of this.llmExecutionTools) {
3100
- await llmExecutionTools.checkConfiguration();
3101
- }
3227
+ // Note: Run checks in parallel
3228
+ await Promise.all(this.llmExecutionTools.map((tools) => tools.checkConfiguration()));
3102
3229
  }
3103
3230
  /**
3104
3231
  * List all available models that can be used
3105
3232
  * This lists is a combination of all available models from all execution tools
3106
3233
  */
3107
3234
  async listModels() {
3108
- const availableModels = [];
3109
- for (const llmExecutionTools of this.llmExecutionTools) {
3110
- // TODO: [🪂] Obtain models in parallel
3111
- const models = await llmExecutionTools.listModels();
3112
- availableModels.push(...models);
3113
- }
3114
- return availableModels;
3235
+ // Obtain all models in parallel and flatten
3236
+ const modelArrays = await Promise.all(this.llmExecutionTools.map((tools) => tools.listModels()));
3237
+ return modelArrays.flat();
3115
3238
  }
3116
3239
  /**
3117
3240
  * Calls the best available chat model
@@ -3267,8 +3390,8 @@ function joinLlmExecutionTools(...llmExecutionTools) {
3267
3390
  /**
3268
3391
  * Extracts all code blocks from markdown.
3269
3392
  *
3270
- * Note: There are multiple simmilar function:
3271
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3393
+ * Note: There are multiple similar functions:
3394
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
3272
3395
  * - `extractJsonBlock` extracts exactly one valid JSON code block
3273
3396
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3274
3397
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
@@ -3318,7 +3441,7 @@ function extractAllBlocksFromMarkdown(markdown) {
3318
3441
  if (currentCodeBlock.content !== '') {
3319
3442
  currentCodeBlock.content += '\n';
3320
3443
  }
3321
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3444
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make proper unescape */;
3322
3445
  }
3323
3446
  }
3324
3447
  if (currentCodeBlock !== null) {
@@ -3338,7 +3461,7 @@ function extractAllBlocksFromMarkdown(markdown) {
3338
3461
  * - When there are multiple JSON code blocks the function throws a `ParseError`
3339
3462
  *
3340
3463
  * Note: It is not important if marked as ```json BUT if it is VALID JSON
3341
- * Note: There are multiple simmilar function:
3464
+ * Note: There are multiple similar function:
3342
3465
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3343
3466
  * - `extractJsonBlock` extracts exactly one valid JSON code block
3344
3467
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
@@ -3363,7 +3486,7 @@ function extractJsonBlock(markdown) {
3363
3486
  }
3364
3487
  /**
3365
3488
  * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3366
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3489
+ * TODO: [🏢] Make this logic part of `JsonFormatParser` or `isValidJsonString`
3367
3490
  */
3368
3491
 
3369
3492
  /**
@@ -3389,7 +3512,7 @@ function arrayableToArray(input) {
3389
3512
  * Just says that the variable is not used but should be kept
3390
3513
  * No side effects.
3391
3514
  *
3392
- * Note: It can be usefull for:
3515
+ * Note: It can be useful for:
3393
3516
  *
3394
3517
  * 1) Suppressing eager optimization of unused imports
3395
3518
  * 2) Suppressing eslint errors of unused variables in the tests
@@ -3816,10 +3939,10 @@ for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
3816
3939
  */
3817
3940
 
3818
3941
  /**
3819
- * @@@
3942
+ * Removes diacritic marks (accents) from characters in a string.
3820
3943
  *
3821
- * @param input @@@
3822
- * @returns @@@
3944
+ * @param input The string containing diacritics to be normalized.
3945
+ * @returns The string with diacritics removed or normalized.
3823
3946
  * @public exported from `@promptbook/utils`
3824
3947
  */
3825
3948
  function removeDiacritics(input) {
@@ -3862,14 +3985,14 @@ const CountUtils = {
3862
3985
  PAGES: countPages,
3863
3986
  };
3864
3987
  /**
3865
- * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3988
+ * TODO: [🧠][🤠] This should be probably as part of `TextFormatParser`
3866
3989
  * Note: [💞] Ignore a discrepancy between file name and entity name
3867
3990
  */
3868
3991
 
3869
3992
  /**
3870
3993
  * Function checkExpectations will check if the expectations on given value are met
3871
3994
  *
3872
- * Note: There are two simmilar functions:
3995
+ * Note: There are two similar functions:
3873
3996
  * - `checkExpectations` which throws an error if the expectations are not met
3874
3997
  * - `isPassingExpectations` which returns a boolean
3875
3998
  *
@@ -3891,7 +4014,7 @@ function checkExpectations(expectations, value) {
3891
4014
  /**
3892
4015
  * Function checkExpectations will check if the expectations on given value are met
3893
4016
  *
3894
- * Note: There are two simmilar functions:
4017
+ * Note: There are two similar functions:
3895
4018
  * - `checkExpectations` which throws an error if the expectations are not met
3896
4019
  * - `isPassingExpectations` which returns a boolean
3897
4020
  *
@@ -3912,13 +4035,17 @@ function isPassingExpectations(expectations, value) {
3912
4035
  }
3913
4036
  /**
3914
4037
  * TODO: [💝] Unite object for expecting amount and format
3915
- * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
4038
+ * TODO: [🧠][🤠] This should be part of `TextFormatParser`
3916
4039
  * Note: [💝] and [🤠] are interconnected together
3917
4040
  */
3918
4041
 
3919
4042
  /**
3920
- * @@@
4043
+ * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
4044
+ * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
4045
+ * Throws errors if execution fails after all attempts.
3921
4046
  *
4047
+ * @param options - The options for execution, including task, parameters, pipeline, and configuration.
4048
+ * @returns The result string of the executed task.
3922
4049
  * @private internal utility of `createPipelineExecutor`
3923
4050
  */
3924
4051
  async function executeAttempts(options) {
@@ -4140,7 +4267,7 @@ async function executeAttempts(options) {
4140
4267
  if (task.format) {
4141
4268
  if (task.format === 'JSON') {
4142
4269
  if (!isValidJsonString($ongoingTaskResult.$resultString || '')) {
4143
- // TODO: [🏢] Do more universally via `FormatDefinition`
4270
+ // TODO: [🏢] Do more universally via `FormatParser`
4144
4271
  try {
4145
4272
  $ongoingTaskResult.$resultString = extractJsonBlock($ongoingTaskResult.$resultString || '');
4146
4273
  }
@@ -4242,12 +4369,16 @@ async function executeAttempts(options) {
4242
4369
  */
4243
4370
 
4244
4371
  /**
4245
- * @@@
4372
+ * Executes a pipeline task that requires mapping or iterating over subvalues of a parameter (such as rows in a CSV).
4373
+ * Handles format and subformat resolution, error handling, and progress reporting.
4374
+ *
4375
+ * @param options - Options for execution, including task details and progress callback.
4376
+ * @returns The result of the subvalue mapping or execution attempts.
4246
4377
  *
4247
4378
  * @private internal utility of `createPipelineExecutor`
4248
4379
  */
4249
4380
  async function executeFormatSubvalues(options) {
4250
- const { task, jokerParameterNames, parameters, priority, csvSettings, pipelineIdentification } = options;
4381
+ const { task, jokerParameterNames, parameters, priority, csvSettings, onProgress, pipelineIdentification } = options;
4251
4382
  if (task.foreach === undefined) {
4252
4383
  return /* not await */ executeAttempts(options);
4253
4384
  }
@@ -4278,16 +4409,16 @@ async function executeFormatSubvalues(options) {
4278
4409
  ${block(pipelineIdentification)}
4279
4410
  `));
4280
4411
  }
4281
- const subvalueDefinition = formatDefinition.subvalueDefinitions.find((subvalueDefinition) => [subvalueDefinition.subvalueName, ...(subvalueDefinition.aliases || [])].includes(task.foreach.subformatName));
4282
- if (subvalueDefinition === undefined) {
4412
+ const subvalueParser = formatDefinition.subvalueParsers.find((subvalueParser) => [subvalueParser.subvalueName, ...(subvalueParser.aliases || [])].includes(task.foreach.subformatName));
4413
+ if (subvalueParser === undefined) {
4283
4414
  throw new UnexpectedError(
4284
4415
  // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4285
4416
  spaceTrim((block) => `
4286
4417
  Unsupported subformat name "${task.foreach.subformatName}" for format "${task.foreach.formatName}"
4287
4418
 
4288
4419
  Available subformat names for format "${formatDefinition.formatName}":
4289
- ${block(formatDefinition.subvalueDefinitions
4290
- .map((subvalueDefinition) => subvalueDefinition.subvalueName)
4420
+ ${block(formatDefinition.subvalueParsers
4421
+ .map((subvalueParser) => subvalueParser.subvalueName)
4291
4422
  .map((subvalueName) => `- ${subvalueName}`)
4292
4423
  .join('\n'))}
4293
4424
 
@@ -4299,55 +4430,85 @@ async function executeFormatSubvalues(options) {
4299
4430
  let formatSettings;
4300
4431
  if (formatDefinition.formatName === 'CSV') {
4301
4432
  formatSettings = csvSettings;
4302
- // <- TODO: [🤹‍♂️] More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4303
- }
4304
- const resultString = await subvalueDefinition.mapValues(parameterValue, task.foreach.outputSubparameterName, formatSettings, async (subparameters, index) => {
4305
- let mappedParameters;
4306
- // TODO: [🤹‍♂️][🪂] Limit to N concurrent executions
4307
- // TODO: When done [🐚] Report progress also for each subvalue here
4308
- try {
4309
- mappedParameters = mapAvailableToExpectedParameters({
4310
- expectedParameters: Object.fromEntries(task.foreach.inputSubparameterNames.map((subparameterName) => [subparameterName, null])),
4311
- availableParameters: subparameters,
4312
- });
4313
- }
4314
- catch (error) {
4315
- if (!(error instanceof PipelineExecutionError)) {
4316
- throw error;
4433
+ // <- TODO: [🤹‍♂️] More universal, make similar pattern for other formats for example \n vs \r\n in text
4434
+ }
4435
+ const resultString = await subvalueParser.mapValues({
4436
+ value: parameterValue,
4437
+ outputParameterName: task.foreach.outputSubparameterName,
4438
+ settings: formatSettings,
4439
+ onProgress(partialResultString) {
4440
+ return onProgress(Object.freeze({
4441
+ [task.resultingParameterName]: partialResultString,
4442
+ }));
4443
+ },
4444
+ async mapCallback(subparameters, index, length) {
4445
+ let mappedParameters;
4446
+ try {
4447
+ mappedParameters = mapAvailableToExpectedParameters({
4448
+ expectedParameters: Object.fromEntries(task.foreach.inputSubparameterNames.map((subparameterName) => [subparameterName, null])),
4449
+ availableParameters: subparameters,
4450
+ });
4317
4451
  }
4318
- throw new PipelineExecutionError(spaceTrim((block) => `
4319
- ${error.message}
4452
+ catch (error) {
4453
+ if (!(error instanceof PipelineExecutionError)) {
4454
+ throw error;
4455
+ }
4456
+ const highLevelError = new PipelineExecutionError(spaceTrim((block) => `
4457
+ ${error.message}
4320
4458
 
4321
- This is error in FOREACH command
4322
- You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command
4459
+ This is error in FOREACH command when mapping ${formatDefinition.formatName} ${subvalueParser.subvalueName} data (${index + 1}/${length})
4460
+ You have probably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command
4323
4461
 
4324
- ${block(pipelineIdentification)}
4325
- Subparameter index: ${index}
4326
- `));
4327
- }
4328
- const allSubparameters = {
4329
- ...parameters,
4330
- ...mappedParameters,
4331
- };
4332
- // 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
4333
- Object.freeze(allSubparameters);
4334
- const subresultString = await executeAttempts({
4335
- ...options,
4336
- priority: priority + index,
4337
- parameters: allSubparameters,
4338
- pipelineIdentification: spaceTrim((block) => `
4339
- ${block(pipelineIdentification)}
4340
- Subparameter index: ${index}
4341
- `),
4342
- });
4343
- return subresultString;
4462
+ ${block(pipelineIdentification)}
4463
+ `));
4464
+ if (length > BIG_DATASET_TRESHOLD) {
4465
+ console.error(highLevelError);
4466
+ return FAILED_VALUE_PLACEHOLDER;
4467
+ }
4468
+ throw highLevelError;
4469
+ }
4470
+ const allSubparameters = {
4471
+ ...parameters,
4472
+ ...mappedParameters,
4473
+ };
4474
+ Object.freeze(allSubparameters);
4475
+ try {
4476
+ const subresultString = await executeAttempts({
4477
+ ...options,
4478
+ priority: priority + index,
4479
+ parameters: allSubparameters,
4480
+ pipelineIdentification: spaceTrim((block) => `
4481
+ ${block(pipelineIdentification)}
4482
+ Subparameter index: ${index}
4483
+ `),
4484
+ });
4485
+ return subresultString;
4486
+ }
4487
+ catch (error) {
4488
+ if (length > BIG_DATASET_TRESHOLD) {
4489
+ console.error(spaceTrim((block) => `
4490
+ ${error.message}
4491
+
4492
+ This is error in FOREACH command when processing ${formatDefinition.formatName} ${subvalueParser.subvalueName} data (${index + 1}/${length})
4493
+
4494
+ ${block(pipelineIdentification)}
4495
+ `));
4496
+ return FAILED_VALUE_PLACEHOLDER;
4497
+ }
4498
+ throw error;
4499
+ }
4500
+ },
4344
4501
  });
4345
4502
  return resultString;
4346
4503
  }
4347
4504
 
4348
4505
  /**
4349
- * @@@
4506
+ * Returns the context for a given task, typically used to provide additional information or variables
4507
+ * required for the execution of the task within a pipeline. The context is returned as a string value
4508
+ * that may include markdown formatting.
4350
4509
  *
4510
+ * @param task - The task for which the context is being generated. This should be a deeply immutable TaskJson object.
4511
+ * @returns The context as a string, formatted as markdown and parameter value.
4351
4512
  * @private internal utility of `createPipelineExecutor`
4352
4513
  */
4353
4514
  async function getContextForTask(task) {
@@ -4355,7 +4516,7 @@ async function getContextForTask(task) {
4355
4516
  }
4356
4517
 
4357
4518
  /**
4358
- * @@@
4519
+ * Retrieves example values or templates for a given task, used to guide or validate pipeline execution.
4359
4520
  *
4360
4521
  * @private internal utility of `createPipelineExecutor`
4361
4522
  */
@@ -4364,91 +4525,128 @@ async function getExamplesForTask(task) {
4364
4525
  }
4365
4526
 
4366
4527
  /**
4367
- * @@@
4528
+ * Computes the cosine similarity between two embedding vectors
4529
+ *
4530
+ * Note: This is helping function for RAG (retrieval-augmented generation)
4531
+ *
4532
+ * @param embeddingVector1
4533
+ * @param embeddingVector2
4534
+ * @returns Cosine similarity between the two vectors
4535
+ *
4536
+ * @public exported from `@promptbook/core`
4537
+ */
4538
+ function computeCosineSimilarity(embeddingVector1, embeddingVector2) {
4539
+ if (embeddingVector1.length !== embeddingVector2.length) {
4540
+ throw new TypeError('Embedding vectors must have the same length');
4541
+ }
4542
+ const dotProduct = embeddingVector1.reduce((sum, value, index) => sum + value * embeddingVector2[index], 0);
4543
+ const magnitude1 = Math.sqrt(embeddingVector1.reduce((sum, value) => sum + value * value, 0));
4544
+ const magnitude2 = Math.sqrt(embeddingVector2.reduce((sum, value) => sum + value * value, 0));
4545
+ return 1 - dotProduct / (magnitude1 * magnitude2);
4546
+ }
4547
+
4548
+ /**
4368
4549
  *
4369
- * Here is the place where RAG (retrieval-augmented generation) happens
4550
+ * @param knowledgePieces
4551
+ * @returns
4552
+ *
4553
+ * @private internal utility of `createPipelineExecutor`
4554
+ */
4555
+ function knowledgePiecesToString(knowledgePieces) {
4556
+ return knowledgePieces
4557
+ .map((knowledgePiece) => {
4558
+ const { content } = knowledgePiece;
4559
+ return `- ${content}`;
4560
+ })
4561
+ .join('\n');
4562
+ // <- TODO: [🧠] Some smarter aggregation of knowledge pieces, single-line vs multi-line vs mixed
4563
+ }
4564
+
4565
+ /**
4566
+ * Retrieves the most relevant knowledge pieces for a given task using embedding-based similarity search.
4567
+ * This is where retrieval-augmented generation (RAG) is performed to enhance the task with external knowledge.
4370
4568
  *
4371
4569
  * @private internal utility of `createPipelineExecutor`
4372
4570
  */
4373
4571
  async function getKnowledgeForTask(options) {
4374
- const { tools, preparedPipeline, task } = options;
4572
+ const { tools, preparedPipeline, task, parameters } = options;
4375
4573
  const firstKnowlegePiece = preparedPipeline.knowledgePieces[0];
4376
4574
  const firstKnowlegeIndex = firstKnowlegePiece === null || firstKnowlegePiece === void 0 ? void 0 : firstKnowlegePiece.index[0];
4377
4575
  // <- TODO: Do not use just first knowledge piece and first index to determine embedding model, use also keyword search
4378
4576
  if (firstKnowlegePiece === undefined || firstKnowlegeIndex === undefined) {
4379
- return 'No knowledge pieces found';
4577
+ return ''; // <- Note: Np knowledge present, return empty string
4380
4578
  }
4381
- // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
4382
- const _llms = arrayableToArray(tools.llm);
4383
- const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
4384
- const taskEmbeddingPrompt = {
4385
- title: 'Knowledge Search',
4386
- modelRequirements: {
4387
- modelVariant: 'EMBEDDING',
4388
- modelName: firstKnowlegeIndex.modelName,
4389
- },
4390
- content: task.content,
4391
- parameters: {
4392
- /* !!!!!!!! */
4393
- },
4394
- };
4395
- const taskEmbeddingResult = await llmTools.callEmbeddingModel(taskEmbeddingPrompt);
4396
- const knowledgePiecesWithRelevance = preparedPipeline.knowledgePieces.map((knowledgePiece) => {
4397
- const { index } = knowledgePiece;
4398
- const knowledgePieceIndex = index.find((i) => i.modelName === firstKnowlegeIndex.modelName);
4399
- // <- TODO: Do not use just first knowledge piece and first index to determine embedding model
4400
- if (knowledgePieceIndex === undefined) {
4579
+ try {
4580
+ // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
4581
+ const _llms = arrayableToArray(tools.llm);
4582
+ const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
4583
+ const taskEmbeddingPrompt = {
4584
+ title: 'Knowledge Search',
4585
+ modelRequirements: {
4586
+ modelVariant: 'EMBEDDING',
4587
+ modelName: firstKnowlegeIndex.modelName,
4588
+ },
4589
+ content: task.content,
4590
+ parameters,
4591
+ };
4592
+ const taskEmbeddingResult = await llmTools.callEmbeddingModel(taskEmbeddingPrompt);
4593
+ const knowledgePiecesWithRelevance = preparedPipeline.knowledgePieces.map((knowledgePiece) => {
4594
+ const { index } = knowledgePiece;
4595
+ const knowledgePieceIndex = index.find((i) => i.modelName === firstKnowlegeIndex.modelName);
4596
+ // <- TODO: Do not use just first knowledge piece and first index to determine embedding model
4597
+ if (knowledgePieceIndex === undefined) {
4598
+ return {
4599
+ content: knowledgePiece.content,
4600
+ relevance: 0,
4601
+ };
4602
+ }
4603
+ const relevance = computeCosineSimilarity(knowledgePieceIndex.position, taskEmbeddingResult.content);
4401
4604
  return {
4402
4605
  content: knowledgePiece.content,
4403
- relevance: 0,
4606
+ relevance,
4404
4607
  };
4405
- }
4406
- const relevance = computeCosineSimilarity(knowledgePieceIndex.position, taskEmbeddingResult.content);
4407
- return {
4408
- content: knowledgePiece.content,
4409
- relevance,
4410
- };
4411
- });
4412
- const knowledgePiecesSorted = knowledgePiecesWithRelevance.sort((a, b) => a.relevance - b.relevance);
4413
- const knowledgePiecesLimited = knowledgePiecesSorted.slice(0, 5);
4414
- console.log('!!! Embedding', {
4415
- task,
4416
- taskEmbeddingPrompt,
4417
- taskEmbeddingResult,
4418
- firstKnowlegePiece,
4419
- firstKnowlegeIndex,
4420
- knowledgePiecesWithRelevance,
4421
- knowledgePiecesSorted,
4422
- knowledgePiecesLimited,
4423
- });
4424
- return knowledgePiecesLimited.map(({ content }) => `- ${content}`).join('\n');
4425
- // <- TODO: [🧠] Some smart aggregation of knowledge pieces, single-line vs multi-line vs mixed
4426
- }
4427
- // TODO: !!!!!! Annotate + to new file
4428
- function computeCosineSimilarity(embeddingVector1, embeddingVector2) {
4429
- if (embeddingVector1.length !== embeddingVector2.length) {
4430
- throw new TypeError('Embedding vectors must have the same length');
4608
+ });
4609
+ const knowledgePiecesSorted = knowledgePiecesWithRelevance.sort((a, b) => a.relevance - b.relevance);
4610
+ const knowledgePiecesLimited = knowledgePiecesSorted.slice(0, 5);
4611
+ /*
4612
+ console.log('`getKnowledgeForTask` Embedding', {
4613
+ task,
4614
+ taskEmbeddingPrompt,
4615
+ taskEmbeddingResult,
4616
+ firstKnowlegePiece,
4617
+ firstKnowlegeIndex,
4618
+ knowledgePiecesWithRelevance,
4619
+ knowledgePiecesSorted,
4620
+ knowledgePiecesLimited,
4621
+ });
4622
+ */
4623
+ return knowledgePiecesToString(knowledgePiecesLimited);
4624
+ }
4625
+ catch (error) {
4626
+ assertsError(error);
4627
+ console.error('Error in `getKnowledgeForTask`', error);
4628
+ // Note: If the LLM fails, just return all knowledge pieces
4629
+ return knowledgePiecesToString(preparedPipeline.knowledgePieces);
4431
4630
  }
4432
- const dotProduct = embeddingVector1.reduce((sum, value, index) => sum + value * embeddingVector2[index], 0);
4433
- const magnitude1 = Math.sqrt(embeddingVector1.reduce((sum, value) => sum + value * value, 0));
4434
- const magnitude2 = Math.sqrt(embeddingVector2.reduce((sum, value) => sum + value * value, 0));
4435
- return 1 - dotProduct / (magnitude1 * magnitude2);
4436
4631
  }
4437
4632
  /**
4438
- * TODO: !!!! Verify if this is working
4439
4633
  * TODO: [♨] Implement Better - use keyword search
4440
4634
  * TODO: [♨] Examples of values
4441
4635
  */
4442
4636
 
4443
4637
  /**
4444
- * @@@
4638
+ * Retrieves all reserved parameters for a given pipeline task, including context, knowledge, examples, and metadata.
4639
+ * Ensures all reserved parameters are defined and throws if any are missing.
4640
+ *
4641
+ * @param options - Options including tools, pipeline, task, and context.
4642
+ * @returns An object containing all reserved parameters for the task.
4445
4643
  *
4446
4644
  * @private internal utility of `createPipelineExecutor`
4447
4645
  */
4448
4646
  async function getReservedParametersForTask(options) {
4449
- const { tools, preparedPipeline, task, pipelineIdentification } = options;
4647
+ const { tools, preparedPipeline, task, parameters, pipelineIdentification, isVerbose } = options;
4450
4648
  const context = await getContextForTask(); // <- [🏍]
4451
- const knowledge = await getKnowledgeForTask({ tools, preparedPipeline, task });
4649
+ const knowledge = await getKnowledgeForTask({ tools, preparedPipeline, task, parameters });
4452
4650
  const examples = await getExamplesForTask();
4453
4651
  const currentDate = new Date().toISOString(); // <- TODO: [🧠][💩] Better
4454
4652
  const modelName = RESERVED_PARAMETER_MISSING_VALUE;
@@ -4460,6 +4658,9 @@ async function getReservedParametersForTask(options) {
4460
4658
  currentDate,
4461
4659
  modelName,
4462
4660
  };
4661
+ if (isVerbose) {
4662
+ console.info('Reserved parameters for task:', { options, reservedParameters });
4663
+ }
4463
4664
  // Note: Doublecheck that ALL reserved parameters are defined:
4464
4665
  for (const parameterName of RESERVED_PARAMETER_NAMES) {
4465
4666
  if (reservedParameters[parameterName] === undefined) {
@@ -4474,23 +4675,21 @@ async function getReservedParametersForTask(options) {
4474
4675
  }
4475
4676
 
4476
4677
  /**
4477
- * @@@
4678
+ * Executes a single task within a pipeline, handling parameter validation, error checking, and progress reporting.
4679
+ *
4680
+ * @param options - Options for execution, including the task, pipeline, parameters, and callbacks.
4681
+ * @returns The output parameters produced by the task.
4478
4682
  *
4479
4683
  * @private internal utility of `createPipelineExecutor`
4480
4684
  */
4481
4685
  async function executeTask(options) {
4482
4686
  const { currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, } = options;
4483
4687
  const priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
4484
- await onProgress({
4485
- outputParameters: {
4486
- [currentTask.resultingParameterName]: '', // <- TODO: [🧠] What is the best value here?
4487
- },
4488
- });
4489
4688
  // Note: Check consistency of used and dependent parameters which was also done in `validatePipeline`, but it’s good to doublecheck
4490
4689
  const usedParameterNames = extractParameterNamesFromTask(currentTask);
4491
4690
  const dependentParameterNames = new Set(currentTask.dependentParameterNames);
4492
4691
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4493
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4692
+ if (difference(union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)), new Set(RESERVED_PARAMETER_NAMES)).size !== 0) {
4494
4693
  throw new UnexpectedError(spaceTrim$1((block) => `
4495
4694
  Dependent parameters are not consistent with used parameters:
4496
4695
 
@@ -4508,13 +4707,16 @@ async function executeTask(options) {
4508
4707
 
4509
4708
  `));
4510
4709
  }
4710
+ const reservedParameters = await getReservedParametersForTask({
4711
+ tools,
4712
+ preparedPipeline,
4713
+ task: currentTask,
4714
+ pipelineIdentification,
4715
+ parameters: parametersToPass,
4716
+ isVerbose,
4717
+ });
4511
4718
  const definedParameters = Object.freeze({
4512
- ...(await getReservedParametersForTask({
4513
- tools,
4514
- preparedPipeline,
4515
- task: currentTask,
4516
- pipelineIdentification,
4517
- })),
4719
+ ...reservedParameters,
4518
4720
  ...parametersToPass,
4519
4721
  });
4520
4722
  const definedParameterNames = new Set(Object.keys(definedParameters));
@@ -4559,6 +4761,7 @@ async function executeTask(options) {
4559
4761
  preparedPipeline,
4560
4762
  tools,
4561
4763
  $executionReport,
4764
+ onProgress,
4562
4765
  pipelineIdentification,
4563
4766
  maxExecutionAttempts,
4564
4767
  maxParallelCount,
@@ -4586,7 +4789,8 @@ async function executeTask(options) {
4586
4789
  */
4587
4790
 
4588
4791
  /**
4589
- * @@@
4792
+ * Filters and returns only the output parameters from the provided pipeline execution options.
4793
+ * Adds warnings for any expected output parameters that are missing.
4590
4794
  *
4591
4795
  * @private internal utility of `createPipelineExecutor`
4592
4796
  */
@@ -4611,9 +4815,12 @@ function filterJustOutputParameters(options) {
4611
4815
  }
4612
4816
 
4613
4817
  /**
4614
- * @@@
4818
+ * Executes an entire pipeline, resolving tasks in dependency order, handling errors, and reporting progress.
4615
4819
  *
4616
- * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4820
+ * Note: This is not a `PipelineExecutor` (which is bound to a single pipeline), but a utility function used by `createPipelineExecutor` to create a `PipelineExecutor`.
4821
+ *
4822
+ * @param options - Options for execution, including input parameters, pipeline, and callbacks.
4823
+ * @returns The result of the pipeline execution, including output parameters, errors, and usage statistics.
4617
4824
  *
4618
4825
  * @private internal utility of `createPipelineExecutor`
4619
4826
  */
@@ -4936,10 +5143,27 @@ function createPipelineExecutor(options) {
4936
5143
  cacheDirname,
4937
5144
  intermediateFilesStrategy,
4938
5145
  isAutoInstalled,
5146
+ }).catch((error) => {
5147
+ assertsError(error);
5148
+ return exportJson({
5149
+ name: 'pipelineExecutorResult',
5150
+ message: `Unuccessful PipelineExecutorResult, last catch`,
5151
+ order: [],
5152
+ value: {
5153
+ isSuccessful: false,
5154
+ errors: [serializeError(error)],
5155
+ warnings: [],
5156
+ usage: UNCERTAIN_USAGE,
5157
+ executionReport: null,
5158
+ outputParameters: {},
5159
+ preparedPipeline,
5160
+ },
5161
+ });
4939
5162
  });
4940
5163
  };
4941
5164
  const pipelineExecutor = (inputParameters) => createTask({
4942
5165
  taskType: 'EXECUTION',
5166
+ title: pipeline.title,
4943
5167
  taskProcessCallback(updateOngoingResult) {
4944
5168
  return pipelineExecutorWithCallback(inputParameters, async (newOngoingResult) => {
4945
5169
  updateOngoingResult(newOngoingResult);
@@ -4991,12 +5215,14 @@ function countUsage(llmTools) {
4991
5215
  const spending = new Subject();
4992
5216
  const proxyTools = {
4993
5217
  get title() {
4994
- // TODO: [🧠] Maybe put here some suffix
4995
- return llmTools.title;
5218
+ return `${llmTools.title} (+usage)`;
5219
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
5220
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(+usage)"?
4996
5221
  },
4997
5222
  get description() {
4998
- // TODO: [🧠] Maybe put here some suffix
4999
- return llmTools.description;
5223
+ return `${llmTools.description} (+usage)`;
5224
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
5225
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(+usage)"?
5000
5226
  },
5001
5227
  checkConfiguration() {
5002
5228
  return /* not await */ llmTools.checkConfiguration();
@@ -5119,7 +5345,8 @@ async function preparePersona(personaDescription, tools, options) {
5119
5345
  */
5120
5346
 
5121
5347
  /**
5122
- * @@@
5348
+ * Safely retrieves the global scope object (window in browser, global in Node.js)
5349
+ * regardless of the JavaScript environment in which the code is running
5123
5350
  *
5124
5351
  * Note: `$` is used to indicate that this function is not a pure function - it access global scope
5125
5352
  *
@@ -5130,10 +5357,10 @@ function $getGlobalScope() {
5130
5357
  }
5131
5358
 
5132
5359
  /**
5133
- * @@@
5360
+ * Normalizes a text string to SCREAMING_CASE (all uppercase with underscores).
5134
5361
  *
5135
- * @param text @@@
5136
- * @returns @@@
5362
+ * @param text The text string to be converted to SCREAMING_CASE format.
5363
+ * @returns The normalized text in SCREAMING_CASE format.
5137
5364
  * @example 'HELLO_WORLD'
5138
5365
  * @example 'I_LOVE_PROMPTBOOK'
5139
5366
  * @public exported from `@promptbook/utils`
@@ -5185,10 +5412,10 @@ function normalizeTo_SCREAMING_CASE(text) {
5185
5412
  */
5186
5413
 
5187
5414
  /**
5188
- * @@@
5415
+ * Normalizes a text string to snake_case format.
5189
5416
  *
5190
- * @param text @@@
5191
- * @returns @@@
5417
+ * @param text The text string to be converted to snake_case format.
5418
+ * @returns The normalized text in snake_case format.
5192
5419
  * @example 'hello_world'
5193
5420
  * @example 'i_love_promptbook'
5194
5421
  * @public exported from `@promptbook/utils`
@@ -5198,11 +5425,11 @@ function normalizeTo_snake_case(text) {
5198
5425
  }
5199
5426
 
5200
5427
  /**
5201
- * Register is @@@
5428
+ * Global registry for storing and managing registered entities of a given type.
5202
5429
  *
5203
5430
  * Note: `$` is used to indicate that this function is not a pure function - it accesses and adds variables in global scope.
5204
5431
  *
5205
- * @private internal utility, exported are only signleton instances of this class
5432
+ * @private internal utility, exported are only singleton instances of this class
5206
5433
  */
5207
5434
  class $Register {
5208
5435
  constructor(registerName) {
@@ -5252,10 +5479,10 @@ class $Register {
5252
5479
  }
5253
5480
 
5254
5481
  /**
5255
- * @@@
5482
+ * Global registry for storing metadata about all available scrapers and converters.
5256
5483
  *
5257
- * Note: `$` is used to indicate that this interacts with the global scope
5258
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
5484
+ * Note: `$` is used to indicate that this interacts with the global scope.
5485
+ * @singleton Only one instance of each register is created per build, but there can be more in different contexts (e.g., tests).
5259
5486
  * @public exported from `@promptbook/core`
5260
5487
  */
5261
5488
  const $scrapersMetadataRegister = new $Register('scrapers_metadata');
@@ -5264,10 +5491,11 @@ const $scrapersMetadataRegister = new $Register('scrapers_metadata');
5264
5491
  */
5265
5492
 
5266
5493
  /**
5267
- * @@@
5494
+ * Registry for all available scrapers in the system.
5495
+ * Central point for registering and accessing different types of content scrapers.
5268
5496
  *
5269
5497
  * Note: `$` is used to indicate that this interacts with the global scope
5270
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
5498
+ * @singleton Only one instance of each register is created per build, but there can be more than one in different build modules
5271
5499
  * @public exported from `@promptbook/core`
5272
5500
  */
5273
5501
  const $scrapersRegister = new $Register('scraper_constructors');
@@ -5363,10 +5591,10 @@ function $registeredScrapersMessage(availableScrapers) {
5363
5591
  */
5364
5592
 
5365
5593
  /**
5366
- * @@@
5594
+ * Converts a given text to kebab-case format.
5367
5595
  *
5368
- * @param text @@@
5369
- * @returns @@@
5596
+ * @param text The text to be converted.
5597
+ * @returns The kebab-case formatted string.
5370
5598
  * @example 'hello-world'
5371
5599
  * @example 'i-love-promptbook'
5372
5600
  * @public exported from `@promptbook/utils`
@@ -5435,7 +5663,8 @@ function knowledgeSourceContentToName(knowledgeSourceContent) {
5435
5663
  */
5436
5664
 
5437
5665
  /**
5438
- * @@@
5666
+ * Converts a name to a properly formatted subfolder path for cache storage.
5667
+ * Handles normalization and path formatting to create consistent cache directory structures.
5439
5668
  *
5440
5669
  * @private for `FileCacheStorage`
5441
5670
  */
@@ -5515,11 +5744,11 @@ function removeEmojis(text) {
5515
5744
  }
5516
5745
 
5517
5746
  /**
5518
- * @@@
5747
+ * Converts a title string into a normalized name.
5519
5748
  *
5520
- * @param value @@@
5521
- * @returns @@@
5522
- * @example @@@
5749
+ * @param value The title string to be converted to a name.
5750
+ * @returns A normalized name derived from the input title.
5751
+ * @example 'Hello World!' -> 'hello-world'
5523
5752
  * @public exported from `@promptbook/utils`
5524
5753
  */
5525
5754
  function titleToName(value) {
@@ -5570,7 +5799,9 @@ const promptbookFetch = async (urlOrRequest, init) => {
5570
5799
  */
5571
5800
 
5572
5801
  /**
5573
- * @@@
5802
+ * Factory function that creates a handler for processing knowledge sources.
5803
+ * Provides standardized processing of different types of knowledge sources
5804
+ * across various scraper implementations.
5574
5805
  *
5575
5806
  * @public exported from `@promptbook/core`
5576
5807
  */
@@ -5709,7 +5940,7 @@ async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5709
5940
  }
5710
5941
 
5711
5942
  /**
5712
- * Prepares the knowle
5943
+ * Prepares the knowledge pieces
5713
5944
  *
5714
5945
  * @see https://github.com/webgptorg/promptbook/discussions/41
5715
5946
  * @public exported from `@promptbook/core`
@@ -5805,15 +6036,18 @@ TODO: [🧊] This is how it can look in future
5805
6036
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
5806
6037
  * Put `knowledgePieces` into `PrepareKnowledgeOptions`
5807
6038
  * TODO: [🪂] More than max things can run in parallel by acident [1,[2a,2b,_],[3a,3b,_]]
5808
- * TODO: [🧠][❎] Do here propper M:N mapping
6039
+ * TODO: [🧠][❎] Do here proper M:N mapping
5809
6040
  * [x] One source can make multiple pieces
5810
6041
  * [ ] One piece can have multiple sources
5811
6042
  */
5812
6043
 
5813
6044
  /**
5814
- * @@@
6045
+ * Prepares tasks by adding knowledge to the prompt and ensuring all necessary parameters are included.
5815
6046
  *
5816
- * @public exported from `@promptbook/core`
6047
+ * @param tasks Sequence of tasks that are chained together to form a pipeline
6048
+ * @returns A promise that resolves to the prepared tasks.
6049
+ *
6050
+ * @private internal utility of `preparePipeline`
5817
6051
  */
5818
6052
  async function prepareTasks(pipeline, tools, options) {
5819
6053
  const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT } = options;
@@ -5851,7 +6085,7 @@ async function prepareTasks(pipeline, tools, options) {
5851
6085
  return { tasksPrepared };
5852
6086
  }
5853
6087
  /**
5854
- * TODO: [😂] Adding knowledge should be convert to async high-level abstractions, simmilar thing with expectations to sync high-level abstractions
6088
+ * TODO: [😂] Adding knowledge should be convert to async high-level abstractions, similar thing with expectations to sync high-level abstractions
5855
6089
  * TODO: [🧠] Add context to each task (if missing)
5856
6090
  * TODO: [🧠] What is better name `prepareTask` or `prepareTaskAndParameters`
5857
6091
  * TODO: [♨][main] !!3 Prepare index the examples and maybe tasks
@@ -5987,7 +6221,7 @@ async function preparePipeline(pipeline, tools, options) {
5987
6221
  order: ORDER_OF_PIPELINE_JSON,
5988
6222
  value: {
5989
6223
  ...pipeline,
5990
- // <- TODO: Probbably deeply clone the pipeline because `$exportJson` freezes the subobjects
6224
+ // <- TODO: Probably deeply clone the pipeline because `$exportJson` freezes the subobjects
5991
6225
  title,
5992
6226
  knowledgeSources: knowledgeSourcesPrepared,
5993
6227
  knowledgePieces: knowledgePiecesPrepared,
@@ -6263,7 +6497,7 @@ const sectionCommandParser = {
6263
6497
  throw new ParseError(`Task section and example section must end with return statement -> {parameterName}`);
6264
6498
  };
6265
6499
  if ($taskJson.content === undefined) {
6266
- throw new UnexpectedError(`Content is missing in the taskJson - probbably commands are applied in wrong order`);
6500
+ throw new UnexpectedError(`Content is missing in the taskJson - probably commands are applied in wrong order`);
6267
6501
  }
6268
6502
  if (command.taskType === 'EXAMPLE') {
6269
6503
  expectResultingParameterName();
@@ -6331,7 +6565,7 @@ const sectionCommandParser = {
6331
6565
  /**
6332
6566
  * Parses the boilerplate command
6333
6567
  *
6334
- * Note: @@@ This command is used as boilerplate for new commands - it should NOT be used in any `.book` file
6568
+ * Note: @@ This command is used as boilerplate for new commands - it should NOT be used in any `.book` file
6335
6569
  *
6336
6570
  * @see `documentationUrl` for more details
6337
6571
  * @private within the commands folder
@@ -6719,11 +6953,11 @@ const expectCommandParser = {
6719
6953
  };
6720
6954
 
6721
6955
  /**
6722
- * @@@
6956
+ * Normalizes a given text to camelCase format.
6723
6957
  *
6724
- * @param text @@@
6725
- * @param _isFirstLetterCapital @@@
6726
- * @returns @@@
6958
+ * @param text The text to be normalized.
6959
+ * @param _isFirstLetterCapital Whether the first letter should be capitalized.
6960
+ * @returns The camelCase formatted string.
6727
6961
  * @example 'helloWorld'
6728
6962
  * @example 'iLovePromptbook'
6729
6963
  * @public exported from `@promptbook/utils`
@@ -6773,9 +7007,9 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
6773
7007
  /**
6774
7008
  * Removes quotes from a string
6775
7009
  *
6776
- * Tip: This is very usefull for post-processing of the result of the LLM model
7010
+ * Tip: This is very useful for post-processing of the result of the LLM model
6777
7011
  * Note: This function removes only the same quotes from the beginning and the end of the string
6778
- * Note: There are two simmilar functions:
7012
+ * Note: There are two similar functions:
6779
7013
  * - `removeQuotes` which removes only bounding quotes
6780
7014
  * - `unwrapResult` which removes whole introduce sentence
6781
7015
  *
@@ -6787,18 +7021,19 @@ function removeQuotes(text) {
6787
7021
  if (text.startsWith('"') && text.endsWith('"')) {
6788
7022
  return text.slice(1, -1);
6789
7023
  }
6790
- if (text.startsWith('\'') && text.endsWith('\'')) {
7024
+ if (text.startsWith("'") && text.endsWith("'")) {
6791
7025
  return text.slice(1, -1);
6792
7026
  }
6793
7027
  return text;
6794
7028
  }
6795
7029
 
6796
7030
  /**
6797
- * Function `validateParameterName` will @@@
7031
+ * Function `validateParameterName` will normalize and validate a parameter name for use in pipelines.
7032
+ * It removes diacritics, emojis, and quotes, normalizes to camelCase, and checks for reserved names and invalid characters.
6798
7033
  *
6799
- * @param parameterName @@@
6800
- * @returns @@@
6801
- * @throws {ParseError} @@@
7034
+ * @param parameterName The parameter name to validate and normalize.
7035
+ * @returns The validated and normalized parameter name.
7036
+ * @throws {ParseError} If the parameter name is empty, reserved, or contains invalid characters.
6802
7037
  * @private within the repository
6803
7038
  */
6804
7039
  function validateParameterName(parameterName) {
@@ -6868,8 +7103,6 @@ function validateParameterName(parameterName) {
6868
7103
  /**
6869
7104
  * Parses the foreach command
6870
7105
  *
6871
- * Note: @@@ This command is used as foreach for new commands - it should NOT be used in any `.book` file
6872
- *
6873
7106
  * @see `documentationUrl` for more details
6874
7107
  * @public exported from `@promptbook/editable`
6875
7108
  */
@@ -6926,14 +7159,14 @@ const foreachCommandParser = {
6926
7159
  `));
6927
7160
  // <- TODO: [🏢] List all supported format names
6928
7161
  }
6929
- const subvalueDefinition = formatDefinition.subvalueDefinitions.find((subvalueDefinition) => [subvalueDefinition.subvalueName, ...(subvalueDefinition.aliases || [])].includes(subformatName));
6930
- if (subvalueDefinition === undefined) {
7162
+ const subvalueParser = formatDefinition.subvalueParsers.find((subvalueParser) => [subvalueParser.subvalueName, ...(subvalueParser.aliases || [])].includes(subformatName));
7163
+ if (subvalueParser === undefined) {
6931
7164
  throw new ParseError(spaceTrim((block) => `
6932
7165
  Unsupported subformat name "${subformatName}" for format "${formatName}"
6933
7166
 
6934
7167
  Available subformat names for format "${formatDefinition.formatName}":
6935
- ${block(formatDefinition.subvalueDefinitions
6936
- .map((subvalueDefinition) => subvalueDefinition.subvalueName)
7168
+ ${block(formatDefinition.subvalueParsers
7169
+ .map((subvalueParser) => subvalueParser.subvalueName)
6937
7170
  .map((subvalueName) => `- ${subvalueName}`)
6938
7171
  .join('\n'))}
6939
7172
  `));
@@ -7110,14 +7343,14 @@ const formatCommandParser = {
7110
7343
  };
7111
7344
 
7112
7345
  /**
7113
- * @@@
7346
+ * Chatbot form factor definition for conversational interfaces that interact with users in a chat-like manner.
7114
7347
  *
7115
7348
  * @public exported from `@promptbook/core`
7116
7349
  */
7117
7350
  const ChatbotFormfactorDefinition = {
7118
7351
  name: 'CHATBOT',
7119
7352
  aliasNames: ['CHAT'],
7120
- description: `@@@`,
7353
+ description: `A chatbot form factor for conversational user interfaces.`,
7121
7354
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/174`,
7122
7355
  pipelineInterface: {
7123
7356
  inputParameters: [
@@ -7144,7 +7377,45 @@ const ChatbotFormfactorDefinition = {
7144
7377
  };
7145
7378
 
7146
7379
  /**
7147
- * Generator is form of app that @@@
7380
+ * Completion is formfactor that emulates completion models
7381
+ *
7382
+ * @public exported from `@promptbook/core`
7383
+ */
7384
+ const CompletionFormfactorDefinition = {
7385
+ name: 'COMPLETION',
7386
+ description: `Completion is formfactor that emulates completion models`,
7387
+ documentationUrl: `https://github.com/webgptorg/promptbook/discussions/@@`,
7388
+ // <- TODO: https://github.com/webgptorg/promptbook/discussions/new?category=concepts
7389
+ // "🔠 Completion Formfactor"
7390
+ pipelineInterface: {
7391
+ inputParameters: [
7392
+ {
7393
+ name: 'inputText',
7394
+ description: `Input text to be completed`,
7395
+ isInput: true,
7396
+ isOutput: false,
7397
+ },
7398
+ {
7399
+ name: 'instructions',
7400
+ description: `Additional instructions for the model, for example the required length, empty by default`,
7401
+ isInput: true,
7402
+ isOutput: false,
7403
+ },
7404
+ ],
7405
+ outputParameters: [
7406
+ {
7407
+ name: 'followingText',
7408
+ description: `Text that follows the input text`,
7409
+ isInput: false,
7410
+ isOutput: true,
7411
+ },
7412
+ ],
7413
+ },
7414
+ };
7415
+
7416
+ /**
7417
+ * Generator form factor represents an application that generates content or data based on user input or predefined rules.
7418
+ * This form factor is used for apps that produce outputs, such as text, images, or other media, based on provided input.
7148
7419
  *
7149
7420
  * @public exported from `@promptbook/core`
7150
7421
  */
@@ -7173,7 +7444,7 @@ const GeneratorFormfactorDefinition = {
7173
7444
  };
7174
7445
 
7175
7446
  /**
7176
- * @@@
7447
+ * Pipeline interface which is equivalent to `any`
7177
7448
  *
7178
7449
  * @see https://github.com/webgptorg/promptbook/discussions/171
7179
7450
  *
@@ -7188,13 +7459,13 @@ const GENERIC_PIPELINE_INTERFACE = {
7188
7459
  */
7189
7460
 
7190
7461
  /**
7191
- * @@@
7462
+ * A generic pipeline
7192
7463
  *
7193
7464
  * @public exported from `@promptbook/core`
7194
7465
  */
7195
7466
  const GenericFormfactorDefinition = {
7196
7467
  name: 'GENERIC',
7197
- description: `@@@`,
7468
+ description: `A generic pipeline`,
7198
7469
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/173`,
7199
7470
  pipelineInterface: GENERIC_PIPELINE_INTERFACE,
7200
7471
  };
@@ -7229,17 +7500,20 @@ const ImageGeneratorFormfactorDefinition = {
7229
7500
  };
7230
7501
 
7231
7502
  /**
7232
- * Matcher is form of app that @@@
7503
+ * Matcher is form of app that evaluates (spreadsheet) content against defined criteria or patterns,
7504
+ * determining if it matches or meets specific requirements. Used for classification,
7505
+ * validation, filtering, and quality assessment of inputs.
7233
7506
  *
7234
7507
  * @public exported from `@promptbook/core`
7235
7508
  */
7236
7509
  const MatcherFormfactorDefinition = {
7237
7510
  name: 'EXPERIMENTAL_MATCHER',
7238
- description: `@@@`,
7511
+ description: `An evaluation system that determines whether content meets specific criteria or patterns.
7512
+ Used for content validation, quality assessment, and intelligent filtering tasks. Currently in experimental phase.`,
7239
7513
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/177`,
7240
7514
  pipelineInterface: {
7241
7515
  inputParameters: [
7242
- /* @@@ */
7516
+ /* Input parameters for content to be matched and criteria to match against */
7243
7517
  {
7244
7518
  name: 'nonce',
7245
7519
  description: 'Just to prevent EXPERIMENTAL_MATCHER to be set as implicit formfactor',
@@ -7248,20 +7522,21 @@ const MatcherFormfactorDefinition = {
7248
7522
  },
7249
7523
  ],
7250
7524
  outputParameters: [
7251
- /* @@@ */
7525
+ /* Output parameters containing match results, confidence scores, and relevant metadata */
7252
7526
  ],
7253
7527
  },
7254
7528
  };
7255
7529
 
7256
7530
  /**
7257
- * Sheets is form of app that @@@
7531
+ * Sheets is form of app that processes tabular data in CSV format, allowing transformation
7532
+ * and analysis of structured data through AI-powered operations
7258
7533
  *
7259
7534
  * @public exported from `@promptbook/core`
7260
7535
  */
7261
7536
  const SheetsFormfactorDefinition = {
7262
7537
  name: 'SHEETS',
7263
7538
  aliasNames: ['SHEETS', 'SHEET'],
7264
- description: `@@@`,
7539
+ description: `A formfactor for processing spreadsheet-like data in CSV format, enabling AI transformations on tabular data`,
7265
7540
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/176`,
7266
7541
  pipelineInterface: {
7267
7542
  inputParameters: [
@@ -7284,13 +7559,16 @@ const SheetsFormfactorDefinition = {
7284
7559
  };
7285
7560
 
7286
7561
  /**
7287
- * Translator is form of app that @@@
7562
+ * Translator is form of app that transforms input text from one form to another,
7563
+ * such as language translation, style conversion, tone modification, or other text transformations.
7288
7564
  *
7289
7565
  * @public exported from `@promptbook/core`
7290
7566
  */
7291
7567
  const TranslatorFormfactorDefinition = {
7292
7568
  name: 'TRANSLATOR',
7293
- description: `@@@`,
7569
+ description: `A text transformation system that converts input content into different forms,
7570
+ including language translations, paraphrasing, style conversions, and tone adjustments.
7571
+ This form factor takes one input and produces one transformed output.`,
7294
7572
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/175`,
7295
7573
  pipelineInterface: {
7296
7574
  inputParameters: [
@@ -7327,6 +7605,8 @@ const FORMFACTOR_DEFINITIONS = [
7327
7605
  MatcherFormfactorDefinition,
7328
7606
  GeneratorFormfactorDefinition,
7329
7607
  ImageGeneratorFormfactorDefinition,
7608
+ CompletionFormfactorDefinition,
7609
+ // <- [🛬] When making new formfactor, copy the _boilerplate and link it here
7330
7610
  ];
7331
7611
  /**
7332
7612
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -7335,7 +7615,7 @@ const FORMFACTOR_DEFINITIONS = [
7335
7615
  /**
7336
7616
  * Parses the formfactor command
7337
7617
  *
7338
- * Note: @@@ This command is used as formfactor for new commands - it should NOT be used in any `.book` file
7618
+ * Note: This command is used as a formfactor for new commands and defines the app type format - it should NOT be used in any `.book` file
7339
7619
  *
7340
7620
  * @see `documentationUrl` for more details
7341
7621
  * @public exported from `@promptbook/editable`
@@ -7357,7 +7637,7 @@ const formfactorCommandParser = {
7357
7637
  /**
7358
7638
  * Description of the FORMFACTOR command
7359
7639
  */
7360
- description: `@@`,
7640
+ description: `Specifies the application type and interface requirements that this promptbook should conform to`,
7361
7641
  /**
7362
7642
  * Link to documentation
7363
7643
  */
@@ -7500,8 +7780,7 @@ const jokerCommandParser = {
7500
7780
  };
7501
7781
 
7502
7782
  /**
7503
- * @@@
7504
- *
7783
+ * @see {@link ModelVariant}
7505
7784
  * @public exported from `@promptbook/core`
7506
7785
  */
7507
7786
  const MODEL_VARIANTS = ['COMPLETION', 'CHAT', 'EMBEDDING' /* <- TODO [🏳] */ /* <- [🤖] */];
@@ -7933,10 +8212,10 @@ function $applyToTaskJson(command, $taskJson, $pipelineJson) {
7933
8212
  }
7934
8213
 
7935
8214
  /**
7936
- * @@@
8215
+ * Checks if the given value is a valid JavaScript identifier name.
7937
8216
  *
7938
- * @param javascriptName @@@
7939
- * @returns @@@
8217
+ * @param javascriptName The value to check for JavaScript identifier validity.
8218
+ * @returns `true` if the value is a valid JavaScript name, false otherwise.
7940
8219
  * @public exported from `@promptbook/utils`
7941
8220
  */
7942
8221
  function isValidJavascriptName(javascriptName) {
@@ -8397,7 +8676,7 @@ function parseCommand(raw, usagePlace) {
8397
8676
  // Arg1 Arg2 Arg3 | FOO
8398
8677
  {
8399
8678
  const commandNameRaw = items.slice(-1).join('_');
8400
- const args = items.slice(0, -1); // <- Note: This is probbably not correct
8679
+ const args = items.slice(0, -1); // <- Note: This is probably not correct
8401
8680
  const rawArgs = raw
8402
8681
  .substring(0, raw.length - commandNameRaw.length)
8403
8682
  .trim();
@@ -8416,7 +8695,10 @@ function parseCommand(raw, usagePlace) {
8416
8695
  `));
8417
8696
  }
8418
8697
  /**
8419
- * @@@
8698
+ * Generates a markdown-formatted message listing all supported commands
8699
+ * with their descriptions and documentation links
8700
+ *
8701
+ * @returns A formatted markdown string containing all available commands and their details
8420
8702
  */
8421
8703
  function getSupportedCommandsMessage() {
8422
8704
  return COMMANDS.flatMap(({ name, aliasNames, description, documentationUrl }) =>
@@ -8427,7 +8709,10 @@ function getSupportedCommandsMessage() {
8427
8709
  ]).join('\n');
8428
8710
  }
8429
8711
  /**
8430
- * @@@
8712
+ * Attempts to parse a command variant using the provided input parameters
8713
+ *
8714
+ * @param input Object containing command parsing information including raw command text and normalized values
8715
+ * @returns A parsed Command object if successful, or null if the command cannot be parsed
8431
8716
  */
8432
8717
  function parseCommandVariant(input) {
8433
8718
  const { commandNameRaw, usagePlace, normalized, args, raw, rawArgs } = input;
@@ -8474,7 +8759,7 @@ function parseCommandVariant(input) {
8474
8759
  }
8475
8760
 
8476
8761
  /**
8477
- * @@@
8762
+ * Extracts the interface (input and output parameters) from a pipeline.
8478
8763
  *
8479
8764
  * @deprecated https://github.com/webgptorg/promptbook/pull/186
8480
8765
  * @see https://github.com/webgptorg/promptbook/discussions/171
@@ -8507,7 +8792,7 @@ function getPipelineInterface(pipeline) {
8507
8792
  }
8508
8793
 
8509
8794
  /**
8510
- * @@@
8795
+ * Checks if two pipeline interfaces are structurally identical.
8511
8796
  *
8512
8797
  * @deprecated https://github.com/webgptorg/promptbook/pull/186
8513
8798
  * @see https://github.com/webgptorg/promptbook/discussions/171
@@ -8539,10 +8824,11 @@ function isPipelineInterfacesEqual(pipelineInterface1, pipelineInterface2) {
8539
8824
  }
8540
8825
 
8541
8826
  /**
8542
- * @@@
8827
+ * Checks if a given pipeline satisfies the requirements of a specified pipeline interface.
8543
8828
  *
8544
8829
  * @deprecated https://github.com/webgptorg/promptbook/pull/186
8545
8830
  * @see https://github.com/webgptorg/promptbook/discussions/171
8831
+ * @returns `true` if the pipeline implements the interface, `false` otherwise.
8546
8832
  *
8547
8833
  * @public exported from `@promptbook/core`
8548
8834
  */
@@ -8728,7 +9014,8 @@ function removeMarkdownComments(content) {
8728
9014
  }
8729
9015
 
8730
9016
  /**
8731
- * @@@
9017
+ * Utility to determine if a pipeline string is in flat format.
9018
+ * A flat pipeline is a simple text without proper structure (headers, blocks, etc).
8732
9019
  *
8733
9020
  * @public exported from `@promptbook/editable`
8734
9021
  */
@@ -8749,7 +9036,10 @@ function isFlatPipeline(pipelineString) {
8749
9036
  }
8750
9037
 
8751
9038
  /**
8752
- * @@@
9039
+ * Converts a pipeline structure to its string representation.
9040
+ *
9041
+ * Transforms a flat, simple pipeline into a properly formatted pipeline string
9042
+ * with sections for title, prompt, and return statement.
8753
9043
  *
8754
9044
  * @public exported from `@promptbook/editable`
8755
9045
  */
@@ -8806,7 +9096,7 @@ function deflatePipeline(pipelineString) {
8806
9096
  * Note: It can not work with html syntax and comments
8807
9097
  *
8808
9098
  * @param markdown any valid markdown
8809
- * @returns @@@
9099
+ * @returns An array of strings, each representing an individual list item found in the markdown
8810
9100
  * @public exported from `@promptbook/markdown-utils`
8811
9101
  */
8812
9102
  function extractAllListItemsFromMarkdown(markdown) {
@@ -8831,8 +9121,8 @@ function extractAllListItemsFromMarkdown(markdown) {
8831
9121
  *
8832
9122
  * - When there are multiple or no code blocks the function throws a `ParseError`
8833
9123
  *
8834
- * Note: There are multiple simmilar function:
8835
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
9124
+ * Note: There are multiple similar functions:
9125
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
8836
9126
  * - `extractJsonBlock` extracts exactly one valid JSON code block
8837
9127
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
8838
9128
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
@@ -8987,7 +9277,7 @@ function flattenMarkdown(markdown) {
8987
9277
  * Compile pipeline from string (markdown) format to JSON format synchronously
8988
9278
  *
8989
9279
  * Note: There are 3 similar functions:
8990
- * - `compilePipeline` **(preferred)** - which propperly compiles the promptbook and use embedding for external knowledge
9280
+ * - `compilePipeline` **(preferred)** - which properly compiles the promptbook and uses embedding for external knowledge
8991
9281
  * - `parsePipeline` - use only if you need to compile promptbook synchronously and it contains NO external knowledge
8992
9282
  * - `preparePipeline` - just one step in the compilation process
8993
9283
  *
@@ -9424,7 +9714,7 @@ function parsePipeline(pipelineString) {
9424
9714
  * TODO: Use spaceTrim more effectively
9425
9715
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
9426
9716
  * TODO: [🥞] Not optimal parsing because `splitMarkdownIntoSections` is executed twice with same string, once through `flattenMarkdown` and second directly here
9427
- * TODO: [♈] Probbably move expectations from tasks to parameters
9717
+ * TODO: [♈] Probably move expectations from tasks to parameters
9428
9718
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
9429
9719
  * TODO: [🍙] Make some standard order of json properties
9430
9720
  */
@@ -9511,45 +9801,43 @@ function addAutoGeneratedSection(content, options) {
9511
9801
  */
9512
9802
  function renderPromptbookMermaid(pipelineJson, options) {
9513
9803
  const { linkTask = () => null } = options || {};
9804
+ const MERMAID_PREFIX = 'pipeline_';
9805
+ const MERMAID_KNOWLEDGE_NAME = MERMAID_PREFIX + 'knowledge';
9806
+ const MERMAID_RESERVED_NAME = MERMAID_PREFIX + 'reserved';
9807
+ const MERMAID_INPUT_NAME = MERMAID_PREFIX + 'input';
9808
+ const MERMAID_OUTPUT_NAME = MERMAID_PREFIX + 'output';
9514
9809
  const parameterNameToTaskName = (parameterName) => {
9810
+ if (parameterName === 'knowledge') {
9811
+ return MERMAID_KNOWLEDGE_NAME;
9812
+ }
9813
+ else if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
9814
+ return MERMAID_RESERVED_NAME;
9815
+ }
9515
9816
  const parameter = pipelineJson.parameters.find((parameter) => parameter.name === parameterName);
9516
9817
  if (!parameter) {
9517
9818
  throw new UnexpectedError(`Could not find {${parameterName}}`);
9518
- // <- TODO: !!6 This causes problems when {knowledge} and other reserved parameters are used
9819
+ // <- TODO: This causes problems when {knowledge} and other reserved parameters are used
9519
9820
  }
9520
9821
  if (parameter.isInput) {
9521
- return 'input';
9822
+ return MERMAID_INPUT_NAME;
9522
9823
  }
9523
9824
  const task = pipelineJson.tasks.find((task) => task.resultingParameterName === parameterName);
9524
9825
  if (!task) {
9525
9826
  throw new Error(`Could not find task for {${parameterName}}`);
9526
9827
  }
9527
- return task.name || normalizeTo_camelCase('task-' + titleToName(task.title));
9828
+ return MERMAID_PREFIX + (task.name || normalizeTo_camelCase('task-' + titleToName(task.title)));
9528
9829
  };
9529
- const promptbookMermaid = spaceTrim$1((block) => `
9530
-
9531
- %% 🔮 Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually
9532
-
9533
- flowchart LR
9534
- subgraph "${pipelineJson.title}"
9535
-
9536
- direction TB
9537
-
9538
- input((Input)):::input
9539
- ${block(pipelineJson.tasks
9830
+ const inputAndIntermediateParametersMermaid = pipelineJson.tasks
9540
9831
  .flatMap(({ title, dependentParameterNames, resultingParameterName }) => [
9541
9832
  `${parameterNameToTaskName(resultingParameterName)}("${title}")`,
9542
9833
  ...dependentParameterNames.map((dependentParameterName) => `${parameterNameToTaskName(dependentParameterName)}--"{${dependentParameterName}}"-->${parameterNameToTaskName(resultingParameterName)}`),
9543
9834
  ])
9544
- .join('\n'))}
9545
-
9546
- ${block(pipelineJson.parameters
9835
+ .join('\n');
9836
+ const outputParametersMermaid = pipelineJson.parameters
9547
9837
  .filter(({ isOutput }) => isOutput)
9548
- .map(({ name }) => `${parameterNameToTaskName(name)}--"{${name}}"-->output`)
9549
- .join('\n'))}
9550
- output((Output)):::output
9551
-
9552
- ${block(pipelineJson.tasks
9838
+ .map(({ name }) => `${parameterNameToTaskName(name)}--"{${name}}"-->${MERMAID_OUTPUT_NAME}`)
9839
+ .join('\n');
9840
+ const linksMermaid = pipelineJson.tasks
9553
9841
  .map((task) => {
9554
9842
  const link = linkTask(task);
9555
9843
  if (link === null) {
@@ -9560,10 +9848,44 @@ function renderPromptbookMermaid(pipelineJson, options) {
9560
9848
  return `click ${taskName} href "${href}" "${title}";`;
9561
9849
  })
9562
9850
  .filter((line) => line !== '')
9563
- .join('\n'))}
9851
+ .join('\n');
9852
+ const interactionPointsMermaid = Object.entries({
9853
+ [MERMAID_INPUT_NAME]: 'Input',
9854
+ [MERMAID_OUTPUT_NAME]: 'Output',
9855
+ [MERMAID_RESERVED_NAME]: 'Other',
9856
+ [MERMAID_KNOWLEDGE_NAME]: 'Knowledge',
9857
+ })
9858
+ .filter(([MERMAID_NAME]) => (inputAndIntermediateParametersMermaid + outputParametersMermaid).includes(MERMAID_NAME))
9859
+ .map(([MERMAID_NAME, title]) => `${MERMAID_NAME}((${title})):::${MERMAID_NAME}`)
9860
+ .join('\n');
9861
+ const promptbookMermaid = spaceTrim$1((block) => `
9862
+
9863
+ %% 🔮 Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually
9864
+
9865
+ flowchart LR
9866
+ subgraph "${pipelineJson.title}"
9867
+
9868
+ %% Basic configuration
9869
+ direction TB
9870
+
9871
+ %% Interaction points from pipeline to outside
9872
+ ${block(interactionPointsMermaid)}
9873
+
9874
+ %% Input and intermediate parameters
9875
+ ${block(inputAndIntermediateParametersMermaid)}
9876
+
9877
+
9878
+ %% Output parameters
9879
+ ${block(outputParametersMermaid)}
9880
+
9881
+ %% Links
9882
+ ${block(linksMermaid)}
9564
9883
 
9565
- classDef input color: grey;
9566
- classDef output color: grey;
9884
+ %% Styles
9885
+ classDef ${MERMAID_INPUT_NAME} color: grey;
9886
+ classDef ${MERMAID_OUTPUT_NAME} color: grey;
9887
+ classDef ${MERMAID_RESERVED_NAME} color: grey;
9888
+ classDef ${MERMAID_KNOWLEDGE_NAME} color: grey;
9567
9889
 
9568
9890
  end;
9569
9891
 
@@ -9640,7 +9962,7 @@ class CallbackInterfaceTools {
9640
9962
  }
9641
9963
 
9642
9964
  /**
9643
- * This error indicates @@@
9965
+ * This error indicates @@
9644
9966
  *
9645
9967
  * @public exported from `@promptbook/core`
9646
9968
  */
@@ -9652,7 +9974,7 @@ class BoilerplateError extends Error {
9652
9974
  }
9653
9975
  }
9654
9976
  /**
9655
- * TODO: @@@ Do not forget to add the error into `0-index.ts` ERRORS
9977
+ * TODO: @@ Do not forget to add the error into `0-index.ts` ERRORS
9656
9978
  */
9657
9979
 
9658
9980
  /**
@@ -9946,7 +10268,7 @@ function executionReportJsonToString(executionReportJson, options) {
9946
10268
  /**
9947
10269
  * Function usageToWorktime will take usage and estimate saved worktime in hours of reading / writing
9948
10270
  *
9949
- * Note: This is an estimate based of theese sources:
10271
+ * Note: This is an estimate based of these sources:
9950
10272
  * - https://jecas.cz/doba-cteni
9951
10273
  * - https://www.originalnitonery.cz/blog/psani-vsemi-deseti-se-muzete-naucit-i-sami-doma
9952
10274
  *
@@ -10011,22 +10333,23 @@ function usageToHuman(usage) {
10011
10333
  */
10012
10334
 
10013
10335
  /**
10014
- * Boilerplate is form of app that @@@
10336
+ * Boilerplate is form of app that serves as a template structure for creating other formfactors
10337
+ * and should not be used directly in production.
10015
10338
  *
10016
10339
  * @public exported from `@promptbook/core`
10017
10340
  */
10018
10341
  const BoilerplateFormfactorDefinition = {
10019
10342
  name: 'BOILERPLATE',
10020
- description: `@@@`,
10343
+ description: `A template structure for creating new formfactors, providing the base architecture and interfaces that should be implemented.`,
10021
10344
  documentationUrl: `https://github.com/webgptorg/promptbook/discussions/@@`,
10022
10345
  // <- TODO: https://github.com/webgptorg/promptbook/discussions/new?category=concepts
10023
10346
  // "🔠 Boilerplate Formfactor"
10024
10347
  pipelineInterface: {
10025
10348
  inputParameters: [
10026
- /* @@@ */
10349
+ /* <- Example input parameters should be defined here */
10027
10350
  ],
10028
10351
  outputParameters: [
10029
- /* @@@ */
10352
+ /* <- Example output parameters should be defined here */
10030
10353
  ],
10031
10354
  },
10032
10355
  };
@@ -10044,8 +10367,13 @@ function filterModels(llmTools, modelFilter) {
10044
10367
  const filteredTools = {
10045
10368
  // Keep all properties from the original llmTools
10046
10369
  ...llmTools,
10370
+ get title() {
10371
+ return `${llmTools.title} (filtered)`;
10372
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
10373
+ },
10047
10374
  get description() {
10048
10375
  return `${llmTools.description} (filtered)`;
10376
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
10049
10377
  },
10050
10378
  // Override listModels to filter the models
10051
10379
  async listModels() {
@@ -10107,10 +10435,10 @@ function filterModels(llmTools, modelFilter) {
10107
10435
  */
10108
10436
 
10109
10437
  /**
10110
- * @@@
10438
+ * Register for LLM tools metadata.
10111
10439
  *
10112
10440
  * Note: `$` is used to indicate that this interacts with the global scope
10113
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
10441
+ * @singleton Only one instance of each register is created per build, but there can be more instances across different builds or environments.
10114
10442
  * @public exported from `@promptbook/core`
10115
10443
  */
10116
10444
  const $llmToolsMetadataRegister = new $Register('llm_tools_metadata');
@@ -10119,10 +10447,10 @@ const $llmToolsMetadataRegister = new $Register('llm_tools_metadata');
10119
10447
  */
10120
10448
 
10121
10449
  /**
10122
- * @@@
10450
+ * Register for LLM tools.
10123
10451
  *
10124
10452
  * Note: `$` is used to indicate that this interacts with the global scope
10125
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
10453
+ * @singleton Only one instance of each register is created per build, but there can be more instances across different builds or environments.
10126
10454
  * @public exported from `@promptbook/core`
10127
10455
  */
10128
10456
  const $llmToolsRegister = new $Register('llm_execution_tools_constructors');
@@ -10273,11 +10601,16 @@ function $registeredLlmToolsMessage() {
10273
10601
  */
10274
10602
 
10275
10603
  /**
10276
- * @@@
10604
+ * Creates LLM execution tools from provided configuration objects
10605
+ *
10606
+ * Instantiates and configures LLM tool instances for each configuration entry,
10607
+ * combining them into a unified interface via MultipleLlmExecutionTools.
10277
10608
  *
10278
10609
  * Note: This function is not cached, every call creates new instance of `MultipleLlmExecutionTools`
10279
10610
  *
10280
- * @returns @@@
10611
+ * @param configuration Array of LLM tool configurations to instantiate
10612
+ * @param options Additional options for configuring the LLM tools
10613
+ * @returns A unified interface combining all successfully instantiated LLM tools
10281
10614
  * @public exported from `@promptbook/core`
10282
10615
  */
10283
10616
  function createLlmToolsFromConfiguration(configuration, options = {}) {
@@ -10316,55 +10649,17 @@ function createLlmToolsFromConfiguration(configuration, options = {}) {
10316
10649
  /**
10317
10650
  * TODO: [🎌] Together with `createLlmToolsFromConfiguration` + 'EXECUTION_TOOLS_CLASSES' gets to `@promptbook/core` ALL model providers, make this more efficient
10318
10651
  * TODO: [🧠][🎌] Dynamically install required providers
10319
- * TODO: @@@ write discussion about this - wizzard
10652
+ * TODO: We should implement an interactive configuration wizard that would:
10653
+ * 1. Detect which LLM providers are available in the environment
10654
+ * 2. Guide users through required configuration settings for each provider
10655
+ * 3. Allow testing connections before completing setup
10656
+ * 4. Generate appropriate configuration code for application integration
10320
10657
  * TODO: [🧠][🍛] Which name is better `createLlmToolsFromConfig` or `createLlmToolsFromConfiguration`?
10321
10658
  * TODO: [🧠] Is there some meaningfull way how to test this util
10322
10659
  * TODO: This should be maybe not under `_common` but under `utils`
10323
10660
  * TODO: [®] DRY Register logic
10324
10661
  */
10325
10662
 
10326
- /**
10327
- * How is the model provider trusted?
10328
- *
10329
- * @public exported from `@promptbook/core`
10330
- */
10331
- const MODEL_TRUST_LEVEL = {
10332
- FULL: `Model is running on the local machine, training data and model weights are known, data are ethically sourced`,
10333
- OPEN: `Model is open source, training data and model weights are known`,
10334
- PARTIALLY_OPEN: `Model is open source, but training data and model weights are not (fully) known`,
10335
- CLOSED_LOCAL: `Model can be run locally, but it is not open source`,
10336
- CLOSED_FREE: `Model is behind API gateway but free to use`,
10337
- CLOSED_BUSINESS: `Model is behind API gateway and paid but has good SLA, TOS, privacy policy and in general is a good to use in business applications`,
10338
- CLOSED: `Model is behind API gateway and paid`,
10339
- UNTRUSTED: `Model has questions about the training data and ethics, but it is not known if it is a problem or not`,
10340
- VURNABLE: `Model has some known serious vulnerabilities, leaks, ethical problems, etc.`,
10341
- };
10342
- // <- TODO: Maybe do better levels of trust
10343
- /**
10344
- * How is the model provider important?
10345
- *
10346
- * @public exported from `@promptbook/core`
10347
- */
10348
- const MODEL_ORDER = {
10349
- /**
10350
- * Top-tier models, e.g. OpenAI, Anthropic,...
10351
- */
10352
- TOP_TIER: 333,
10353
- /**
10354
- * Mid-tier models, e.g. Llama, Mistral, etc.
10355
- */
10356
- NORMAL: 100,
10357
- /**
10358
- * Low-tier models, e.g. Phi, Tiny, etc.
10359
- */
10360
- LOW_TIER: 0,
10361
- };
10362
- /**
10363
- * TODO: Add configuration schema and maybe some documentation link
10364
- * TODO: Maybe constrain LlmToolsConfiguration[number] by generic to ensure that `createConfigurationFromEnv` and `getBoilerplateConfiguration` always create same `packageName` and `className`
10365
- * TODO: [®] DRY Register logic
10366
- */
10367
-
10368
10663
  /**
10369
10664
  * Stores data in memory (HEAP)
10370
10665
  *
@@ -10434,17 +10729,19 @@ function $getCurrentDate() {
10434
10729
  * @public exported from `@promptbook/core`
10435
10730
  */
10436
10731
  function cacheLlmTools(llmTools, options = {}) {
10437
- const { storage = new MemoryStorage(), isCacheReloaded = false } = options;
10732
+ const { storage = new MemoryStorage(), isCacheReloaded = false, isVerbose = DEFAULT_IS_VERBOSE } = options;
10438
10733
  const proxyTools = {
10439
10734
  ...llmTools,
10440
10735
  // <- Note: [🥫]
10441
10736
  get title() {
10442
- // TODO: [🧠] Maybe put here some suffix
10443
- return llmTools.title;
10737
+ return `${llmTools.title} (cached)`;
10738
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
10739
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(cached)"?
10444
10740
  },
10445
10741
  get description() {
10446
- // TODO: [🧠] Maybe put here some suffix
10447
- return llmTools.description;
10742
+ return `${llmTools.description} (cached)`;
10743
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
10744
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(cached)"?
10448
10745
  },
10449
10746
  listModels() {
10450
10747
  // TODO: [🧠] Should be model listing also cached?
@@ -10454,13 +10751,37 @@ function cacheLlmTools(llmTools, options = {}) {
10454
10751
  const callCommonModel = async (prompt) => {
10455
10752
  const { parameters, content, modelRequirements } = prompt;
10456
10753
  // <- Note: These are relevant things from the prompt that the cache key should depend on.
10754
+ // TODO: Maybe some standalone function for normalization of content for cache
10755
+ let normalizedContent = content;
10756
+ normalizedContent = normalizedContent.replace(/\s+/g, ' ');
10757
+ normalizedContent = normalizedContent.split('\r\n').join('\n');
10758
+ normalizedContent = spaceTrim(normalizedContent);
10759
+ // Note: Do not need to save everything in the cache, just the relevant parameters
10760
+ const relevantParameterNames = extractParameterNames(content);
10761
+ const relevantParameters = Object.fromEntries(Object.entries(parameters).filter(([key]) => relevantParameterNames.has(key)));
10762
+ const keyHashBase = { relevantParameters, normalizedContent, modelRequirements };
10457
10763
  const key = titleToName(prompt.title.substring(0, MAX_FILENAME_LENGTH - 10) +
10458
10764
  '-' +
10459
- sha256(hexEncoder.parse(JSON.stringify({ parameters, content, modelRequirements }))).toString( /* hex */));
10765
+ sha256(hexEncoder.parse(JSON.stringify(keyHashBase)))
10766
+ .toString( /* hex */)
10767
+ .substring(0, 10 - 1));
10460
10768
  const cacheItem = !isCacheReloaded ? await storage.getItem(key) : null;
10461
10769
  if (cacheItem) {
10462
10770
  return cacheItem.promptResult;
10463
10771
  }
10772
+ if (isVerbose) {
10773
+ console.info('Cache miss for key:', key, {
10774
+ prompt,
10775
+ 'prompt.title': prompt.title,
10776
+ MAX_FILENAME_LENGTH,
10777
+ keyHashBase,
10778
+ parameters,
10779
+ relevantParameters,
10780
+ content,
10781
+ normalizedContent,
10782
+ modelRequirements,
10783
+ });
10784
+ }
10464
10785
  let promptResult;
10465
10786
  variant: switch (prompt.modelRequirements.modelVariant) {
10466
10787
  case 'CHAT':
@@ -10481,7 +10802,16 @@ function cacheLlmTools(llmTools, options = {}) {
10481
10802
  await storage.setItem(key, {
10482
10803
  date: $getCurrentDate(),
10483
10804
  promptbookVersion: PROMPTBOOK_ENGINE_VERSION,
10484
- prompt,
10805
+ bookVersion: BOOK_LANGUAGE_VERSION,
10806
+ prompt: {
10807
+ ...prompt,
10808
+ parameters: Object.entries(parameters).length === Object.entries(relevantParameters).length
10809
+ ? parameters
10810
+ : {
10811
+ ...relevantParameters,
10812
+ note: `<- Note: Only relevant parameters are stored in the cache`,
10813
+ },
10814
+ },
10485
10815
  promptResult,
10486
10816
  });
10487
10817
  return promptResult;
@@ -10507,13 +10837,13 @@ function cacheLlmTools(llmTools, options = {}) {
10507
10837
  /**
10508
10838
  * TODO: [🧠][💸] Maybe make some common abstraction `interceptLlmTools` and use here (or use javascript Proxy?)
10509
10839
  * TODO: [🧠] Is there some meaningfull way how to test this util
10510
- * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
10511
- * @@@ write discussion about this and storages
10512
- * @@@ write how to combine multiple interceptors
10840
+ * TODO: [👷‍♂️] Comprehensive manual about construction of llmTools
10841
+ * Detailed explanation about caching strategies and appropriate storage selection for different use cases
10842
+ * Examples of how to combine multiple interceptors for advanced caching, logging, and usage tracking
10513
10843
  */
10514
10844
 
10515
10845
  /**
10516
- * @@@
10846
+ * Wraps LlmExecutionTools to limit the total usage based on provided limits.
10517
10847
  *
10518
10848
  * @public exported from `@promptbook/core`
10519
10849
  */
@@ -10565,7 +10895,7 @@ const _AnthropicClaudeMetadataRegistration = $llmToolsMetadataRegister.register(
10565
10895
  className: 'AnthropicClaudeExecutionTools',
10566
10896
  envVariables: ['ANTHROPIC_CLAUDE_API_KEY'],
10567
10897
  trustLevel: 'CLOSED',
10568
- order: MODEL_ORDER.TOP_TIER,
10898
+ order: MODEL_ORDERS.TOP_TIER,
10569
10899
  getBoilerplateConfiguration() {
10570
10900
  return {
10571
10901
  title: 'Anthropic Claude',
@@ -10575,6 +10905,7 @@ const _AnthropicClaudeMetadataRegistration = $llmToolsMetadataRegister.register(
10575
10905
  apiKey: 'sk-ant-api03-',
10576
10906
  isProxied: true,
10577
10907
  remoteServerUrl: DEFAULT_REMOTE_SERVER_URL,
10908
+ maxRequestsPerMinute: DEFAULT_MAX_REQUESTS_PER_MINUTE,
10578
10909
  },
10579
10910
  };
10580
10911
  },
@@ -10610,9 +10941,9 @@ const _AzureOpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10610
10941
  title: 'Azure Open AI',
10611
10942
  packageName: '@promptbook/azure-openai',
10612
10943
  className: 'AzureOpenAiExecutionTools',
10613
- envVariables: ['AZUREOPENAI_RESOURCE_NAME', 'AZUREOPENAI_DEPLOYMENT_NAME', 'AZUREOPENAI_API_KEY'],
10944
+ envVariables: ['AZUREOPENAI_API_KEY', 'AZUREOPENAI_RESOURCE_NAME', 'AZUREOPENAI_DEPLOYMENT_NAME'],
10614
10945
  trustLevel: 'CLOSED_BUSINESS',
10615
- order: MODEL_ORDER.NORMAL,
10946
+ order: MODEL_ORDERS.NORMAL,
10616
10947
  getBoilerplateConfiguration() {
10617
10948
  return {
10618
10949
  title: 'Azure Open AI',
@@ -10620,6 +10951,9 @@ const _AzureOpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10620
10951
  className: 'AzureOpenAiExecutionTools',
10621
10952
  options: {
10622
10953
  apiKey: 'sk-',
10954
+ resourceName: 'my-resource-name',
10955
+ deploymentName: 'my-deployment-name',
10956
+ maxRequestsPerMinute: DEFAULT_MAX_REQUESTS_PER_MINUTE,
10623
10957
  },
10624
10958
  };
10625
10959
  },
@@ -10633,15 +10967,15 @@ const _AzureOpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10633
10967
  packageName: '@promptbook/azure-openai',
10634
10968
  className: 'AzureOpenAiExecutionTools',
10635
10969
  options: {
10970
+ apiKey: env.AZUREOPENAI_API_KEY,
10636
10971
  resourceName: env.AZUREOPENAI_RESOURCE_NAME,
10637
10972
  deploymentName: env.AZUREOPENAI_DEPLOYMENT_NAME,
10638
- apiKey: env.AZUREOPENAI_API_KEY,
10639
10973
  },
10640
10974
  };
10641
10975
  }
10642
- else if (typeof env.AZUREOPENAI_RESOURCE_NAME === 'string' ||
10643
- typeof env.AZUREOPENAI_DEPLOYMENT_NAME === 'string' ||
10644
- typeof env.AZUREOPENAI_API_KEY === 'string') {
10976
+ else if (typeof env.AZUREOPENAI_API_KEY === 'string' ||
10977
+ typeof env.AZUREOPENAI_RESOURCE_NAME === 'string' ||
10978
+ typeof env.AZUREOPENAI_DEPLOYMENT_NAME === 'string') {
10645
10979
  return null;
10646
10980
  /*
10647
10981
  Note: [🗨] Partial configuration is handled more gracefully elsewhere
@@ -10700,7 +11034,7 @@ const _DeepseekMetadataRegistration = $llmToolsMetadataRegister.register({
10700
11034
  className: 'DeepseekExecutionTools',
10701
11035
  envVariables: ['DEEPSEEK_GENERATIVE_AI_API_KEY'],
10702
11036
  trustLevel: 'UNTRUSTED',
10703
- order: MODEL_ORDER.NORMAL,
11037
+ order: MODEL_ORDERS.NORMAL,
10704
11038
  getBoilerplateConfiguration() {
10705
11039
  return {
10706
11040
  title: 'Deepseek',
@@ -10751,7 +11085,7 @@ const _GoogleMetadataRegistration = $llmToolsMetadataRegister.register({
10751
11085
  className: 'GoogleExecutionTools',
10752
11086
  envVariables: ['GOOGLE_GENERATIVE_AI_API_KEY'],
10753
11087
  trustLevel: 'CLOSED',
10754
- order: MODEL_ORDER.NORMAL,
11088
+ order: MODEL_ORDERS.NORMAL,
10755
11089
  getBoilerplateConfiguration() {
10756
11090
  return {
10757
11091
  title: 'Google Gemini',
@@ -10802,7 +11136,7 @@ const _OpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10802
11136
  className: 'OpenAiExecutionTools',
10803
11137
  envVariables: ['OPENAI_API_KEY'],
10804
11138
  trustLevel: 'CLOSED',
10805
- order: MODEL_ORDER.TOP_TIER,
11139
+ order: MODEL_ORDERS.TOP_TIER,
10806
11140
  getBoilerplateConfiguration() {
10807
11141
  return {
10808
11142
  title: 'Open AI',
@@ -10810,6 +11144,7 @@ const _OpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10810
11144
  className: 'OpenAiExecutionTools',
10811
11145
  options: {
10812
11146
  apiKey: 'sk-',
11147
+ maxRequestsPerMinute: DEFAULT_MAX_REQUESTS_PER_MINUTE,
10813
11148
  },
10814
11149
  };
10815
11150
  },
@@ -10829,9 +11164,9 @@ const _OpenAiMetadataRegistration = $llmToolsMetadataRegister.register({
10829
11164
  },
10830
11165
  });
10831
11166
  /**
10832
- * @@@ registration1 of default configuration for Open AI
11167
+ * Registration of the OpenAI Assistant metadata
10833
11168
  *
10834
- * Note: [🏐] Configurations registrations are done in @@@ BUT constructor @@@
11169
+ * Note: [🏐] Configurations registrations are done in the metadata registration section, but the constructor registration is handled separately.
10835
11170
  *
10836
11171
  * @public exported from `@promptbook/core`
10837
11172
  * @public exported from `@promptbook/wizzard`
@@ -10844,7 +11179,7 @@ const _OpenAiAssistantMetadataRegistration = $llmToolsMetadataRegister.register(
10844
11179
  envVariables: null,
10845
11180
  // <- TODO: ['OPENAI_API_KEY', 'OPENAI_ASSISTANT_ID']
10846
11181
  trustLevel: 'CLOSED',
10847
- order: MODEL_ORDER.NORMAL,
11182
+ order: MODEL_ORDERS.NORMAL,
10848
11183
  getBoilerplateConfiguration() {
10849
11184
  return {
10850
11185
  title: 'Open AI Assistant',
@@ -10853,6 +11188,7 @@ const _OpenAiAssistantMetadataRegistration = $llmToolsMetadataRegister.register(
10853
11188
  options: {
10854
11189
  apiKey: 'sk-',
10855
11190
  assistantId: 'asst_',
11191
+ maxRequestsPerMinute: DEFAULT_MAX_REQUESTS_PER_MINUTE,
10856
11192
  },
10857
11193
  };
10858
11194
  },
@@ -10879,6 +11215,52 @@ const _OpenAiAssistantMetadataRegistration = $llmToolsMetadataRegister.register(
10879
11215
  * Note: [💞] Ignore a discrepancy between file name and entity name
10880
11216
  */
10881
11217
 
11218
+ /**
11219
+ * Migrates the pipeline to the latest version
11220
+ *
11221
+ * Note: Migration does not do heavy lifting like calling the LLMs, just lightweight changes of the structure
11222
+ *
11223
+ * @public exported from `@promptbook/core`
11224
+ */
11225
+ function migratePipeline(deprecatedPipeline) {
11226
+ /* eslint-disable prefer-const */
11227
+ let { pipelineUrl, sourceFile, title, bookVersion, description, formfactorName, parameters, tasks, knowledgeSources, knowledgePieces, personas, preparations, sources, } = deprecatedPipeline;
11228
+ let isChanged = false;
11229
+ personas = personas.map((persona) => {
11230
+ const migratedPersona = { ...persona }; /* <- TODO: [🌪] */
11231
+ if (migratedPersona.modelRequirements !== undefined) {
11232
+ isChanged = true;
11233
+ migratedPersona.modelsRequirements = [migratedPersona.modelRequirements];
11234
+ delete migratedPersona.modelRequirements;
11235
+ }
11236
+ return migratedPersona;
11237
+ });
11238
+ if (!isChanged) {
11239
+ // Note: If nothing to migrate, return the same pipeline
11240
+ return deprecatedPipeline;
11241
+ }
11242
+ const migratedPipeline = {
11243
+ pipelineUrl,
11244
+ sourceFile,
11245
+ title,
11246
+ bookVersion,
11247
+ description,
11248
+ formfactorName,
11249
+ parameters,
11250
+ tasks,
11251
+ knowledgeSources,
11252
+ knowledgePieces,
11253
+ personas,
11254
+ preparations,
11255
+ sources,
11256
+ // <- TODO: [🍙] Make some standard order of json properties
11257
+ };
11258
+ console.info(`Book automatically migrated`, { deprecatedPipeline, migratedPipeline });
11259
+ // console.info(`Book automatically migrated from ${} -> ${}`, {deprecatedPipeline,migratedPipeline})
11260
+ // <- TODO: Report the versions of the migration, DO not migrate backwards, throw `CompatibilityError` when given newer version than current version of the engine and link the NPM + Docker packages
11261
+ return migratedPipeline;
11262
+ }
11263
+
10882
11264
  /**
10883
11265
  * Function `isValidPipelineString` will validate the if the string is a valid pipeline string
10884
11266
  * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
@@ -10964,8 +11346,8 @@ function prompt(strings, ...values) {
10964
11346
  * 2) `promptTemplate` alias for `prompt`
10965
11347
  * 3) `book` for notating and validating entire books exported from `@promptbook/utils`
10966
11348
  *
10967
- * @param strings @@@
10968
- * @param values @@@
11349
+ * @param strings The static string parts of the template literal
11350
+ * @param values The dynamic values embedded within the template literal used as data
10969
11351
  * @returns the pipeline string
10970
11352
  * @public exported from `@promptbook/core`
10971
11353
  */
@@ -11032,14 +11414,14 @@ const boilerplateScraperMetadata = $deepFreeze({
11032
11414
  packageName: '@promptbook/boilerplate',
11033
11415
  className: 'BoilerplateScraper',
11034
11416
  mimeTypes: [
11035
- '@@@/@@@',
11036
- // <- TODO: @@@ Add compatible mime types with Boilerplate scraper
11417
+ '@@/@@',
11418
+ // <- TODO: @@ Add compatible mime types with Boilerplate scraper
11037
11419
  ],
11038
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@@',
11420
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
11039
11421
  isAvilableInBrowser: false,
11040
11422
  // <- Note: [🌏] Only `MarkdownScraper` makes sense to be available in the browser, for scraping non-markdown sources in the browser use a remote server
11041
11423
  requiredExecutables: [
11042
- /* @@@ 'Pandoc' */
11424
+ /* @@ 'Pandoc' */
11043
11425
  ],
11044
11426
  }); /* <- Note: [🤛] */
11045
11427
  /**
@@ -11311,5 +11693,5 @@ class PrefixStorage {
11311
11693
  }
11312
11694
  }
11313
11695
 
11314
- export { $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, AbstractFormatError, AuthenticationError, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CsvFormatDefinition, CsvFormatError, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_TITLE, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FORMFACTOR_DEFINITIONS, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_ORDER, MODEL_TRUST_LEVEL, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotFoundError, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, PLAYGROUND_APP_ID, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, REMOTE_SERVER_URLS, RESERVED_PARAMETER_NAMES, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatDefinition, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, UnexpectedError, WrappedError, ZERO_USAGE, ZERO_VALUE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, addUsage, book, cacheLlmTools, collectionToJson, compilePipeline, countUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, filterModels, getPipelineInterface, identificationToPromptbookToken, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, parsePipeline, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTasks, prettifyPipelineString, promptbookFetch, promptbookTokenToIdentification, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline, validatePipelineString };
11696
+ export { $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, AbstractFormatError, AuthenticationError, BIG_DATASET_TRESHOLD, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CompletionFormfactorDefinition, CsvFormatError, CsvFormatParser, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_MAX_REQUESTS_PER_MINUTE, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_TITLE, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FAILED_VALUE_PLACEHOLDER, FORMFACTOR_DEFINITIONS, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_ORDERS, MODEL_TRUST_LEVELS, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotFoundError, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, PENDING_VALUE_PLACEHOLDER, PLAYGROUND_APP_ID, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, REMOTE_SERVER_URLS, RESERVED_PARAMETER_NAMES, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatParser, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, UnexpectedError, WrappedError, ZERO_USAGE, ZERO_VALUE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, addUsage, book, cacheLlmTools, collectionToJson, compilePipeline, computeCosineSimilarity, countUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, filterModels, getPipelineInterface, identificationToPromptbookToken, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, migratePipeline, parsePipeline, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prettifyPipelineString, promptbookFetch, promptbookTokenToIdentification, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline, validatePipelineString };
11315
11697
  //# sourceMappingURL=index.es.js.map