@promptbook/remote-server 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 +597 -401
  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 +15 -3
  198. package/umd/index.umd.js +601 -405
  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/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('express'), require('http'), require('socket.io'), require('spacetrim'), require('express-openapi-validator'), require('swagger-ui-express'), require('waitasecond'), require('crypto'), require('child_process'), require('fs/promises'), require('path'), require('rxjs'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('papaparse')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'express', 'http', 'socket.io', 'spacetrim', 'express-openapi-validator', 'swagger-ui-express', 'waitasecond', 'crypto', 'child_process', 'fs/promises', 'path', 'rxjs', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'papaparse'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-remote-server"] = {}, global.colors, global.express, global.http, global.socket_io, global.spaceTrim, global.OpenApiValidator, global.swaggerUi, global.waitasecond, global.crypto, global.child_process, global.promises, global.path, global.rxjs, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.papaparse));
5
- })(this, (function (exports, colors, express, http, socket_io, spaceTrim, OpenApiValidator, swaggerUi, waitasecond, crypto, child_process, promises, path, rxjs, prettier, parserHtml, hexEncoder, sha256, cryptoJs, mimeTypes, papaparse) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('express'), require('express-openapi-validator'), require('http'), require('socket.io'), require('spacetrim'), require('swagger-ui-express'), require('waitasecond'), require('crypto'), require('child_process'), require('fs/promises'), require('path'), require('rxjs'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('papaparse')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'express', 'express-openapi-validator', 'http', 'socket.io', 'spacetrim', 'swagger-ui-express', 'waitasecond', 'crypto', 'child_process', 'fs/promises', 'path', 'rxjs', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'papaparse'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-remote-server"] = {}, global.colors, global.express, global.OpenApiValidator, global.http, global.socket_io, global.spaceTrim, global.swaggerUi, global.waitasecond, global.crypto, global.child_process, global.promises, global.path, global.rxjs, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.papaparse));
5
+ })(this, (function (exports, colors, express, OpenApiValidator, http, socket_io, spaceTrim, swaggerUi, waitasecond, crypto, child_process, promises, path, rxjs, prettier, parserHtml, hexEncoder, sha256, cryptoJs, mimeTypes, papaparse) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -26,9 +26,9 @@
26
26
 
27
27
  var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
28
28
  var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
29
+ var OpenApiValidator__namespace = /*#__PURE__*/_interopNamespace(OpenApiValidator);
29
30
  var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
30
31
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
31
- var OpenApiValidator__namespace = /*#__PURE__*/_interopNamespace(OpenApiValidator);
32
32
  var swaggerUi__default = /*#__PURE__*/_interopDefaultLegacy(swaggerUi);
33
33
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
34
34
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
@@ -48,7 +48,7 @@
48
48
  * @generated
49
49
  * @see https://github.com/webgptorg/promptbook
50
50
  */
51
- const PROMPTBOOK_ENGINE_VERSION = '0.92.0-9';
51
+ const PROMPTBOOK_ENGINE_VERSION = '0.93.0';
52
52
  /**
53
53
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
54
54
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -58,7 +58,7 @@
58
58
  * Returns the same value that is passed as argument.
59
59
  * No side effects.
60
60
  *
61
- * Note: It can be usefull for:
61
+ * Note: It can be useful for:
62
62
  *
63
63
  * 1) Leveling indentation
64
64
  * 2) Putting always-true or always-false conditions without getting eslint errors
@@ -115,6 +115,21 @@
115
115
  * @public exported from `@promptbook/core`
116
116
  */
117
117
  const DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
118
+ /**
119
+ * Threshold value that determines when a dataset is considered "big"
120
+ * and may require special handling or optimizations
121
+ *
122
+ * For example, when error occurs in one item of the big dataset, it will not fail the whole pipeline
123
+ *
124
+ * @public exported from `@promptbook/core`
125
+ */
126
+ const BIG_DATASET_TRESHOLD = 50;
127
+ /**
128
+ * Placeholder text used to represent a placeholder value of failed operation
129
+ *
130
+ * @public exported from `@promptbook/core`
131
+ */
132
+ const FAILED_VALUE_PLACEHOLDER = '!?';
118
133
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
119
134
  /**
120
135
  * The maximum number of iterations for a loops
@@ -194,7 +209,7 @@
194
209
  const DEFAULT_SCRAPE_CACHE_DIRNAME = './.promptbook/scrape-cache';
195
210
  // <- TODO: [🧜‍♂️]
196
211
  /**
197
- * @@@
212
+ * Default settings for parsing and generating CSV files in Promptbook.
198
213
  *
199
214
  * @public exported from `@promptbook/core`
200
215
  */
@@ -205,19 +220,19 @@
205
220
  skipEmptyLines: true,
206
221
  });
207
222
  /**
208
- * @@@
223
+ * Controls whether verbose logging is enabled by default throughout the application.
209
224
  *
210
225
  * @public exported from `@promptbook/core`
211
226
  */
212
227
  let DEFAULT_IS_VERBOSE = false;
213
228
  /**
214
- * @@@
229
+ * Controls whether auto-installation of dependencies is enabled by default.
215
230
  *
216
231
  * @public exported from `@promptbook/core`
217
232
  */
218
233
  const DEFAULT_IS_AUTO_INSTALLED = false;
219
234
  /**
220
- * @@@
235
+ * Indicates whether pipeline logic validation is enabled. When true, the pipeline logic is checked for consistency.
221
236
  *
222
237
  * @private within the repository
223
238
  */
@@ -285,7 +300,7 @@
285
300
  ${block(message)}
286
301
 
287
302
  Note: This error should not happen.
288
- It's probbably a bug in the pipeline collection
303
+ It's probably a bug in the pipeline collection
289
304
 
290
305
  Please report issue:
291
306
  ${block(getErrorReportUrl(new Error(message)).href)}
@@ -385,7 +400,7 @@
385
400
  super(message);
386
401
  this.name = 'PipelineExecutionError';
387
402
  // TODO: [🐙] DRY - Maybe $randomId
388
- this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid simmilar char conflicts */)}`;
403
+ this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
389
404
  Object.setPrototypeOf(this, PipelineExecutionError.prototype);
390
405
  }
391
406
  }
@@ -424,7 +439,7 @@
424
439
  }
425
440
 
426
441
  /**
427
- * This error indicates that the pipeline collection cannot be propperly loaded
442
+ * This error indicates that the pipeline collection cannot be properly loaded
428
443
  *
429
444
  * @public exported from `@promptbook/core`
430
445
  */
@@ -501,7 +516,7 @@
501
516
  super(spaceTrim.spaceTrim((block) => `
502
517
  ${block(message)}
503
518
 
504
- Note: You have probbably forgot to provide some tools for pipeline execution or preparation
519
+ Note: You have probably forgot to provide some tools for pipeline execution or preparation
505
520
 
506
521
  `));
507
522
  this.name = 'MissingToolsError';
@@ -872,7 +887,8 @@
872
887
  */
873
888
 
874
889
  /**
875
- * @@@
890
+ * Attempts to locate the specified application on a Linux system using the 'which' command.
891
+ * Returns the path to the executable if found, or null otherwise.
876
892
  *
877
893
  * @private within the repository
878
894
  */
@@ -892,7 +908,8 @@
892
908
  */
893
909
 
894
910
  /**
895
- * @@@
911
+ * Provides filesystem access (for example for Node.js-based scrapers)
912
+ * Creates a standardized filesystem interface that scrapers can use for file operations.
896
913
  *
897
914
  * @public exported from `@promptbook/node`
898
915
  */
@@ -938,7 +955,8 @@
938
955
  // eslint-disable-next-line @typescript-eslint/no-var-requires
939
956
  const userhome = require('userhome');
940
957
  /**
941
- * @@@
958
+ * Attempts to locate the specified application on a macOS system by checking standard application paths and using mdfind.
959
+ * Returns the path to the executable if found, or null otherwise.
942
960
  *
943
961
  * @private within the repository
944
962
  */
@@ -970,7 +988,8 @@
970
988
  */
971
989
 
972
990
  /**
973
- * @@@
991
+ * Attempts to locate the specified application on a Windows system by searching common installation directories.
992
+ * Returns the path to the executable if found, or null otherwise.
974
993
  *
975
994
  * @private within the repository
976
995
  */
@@ -1041,7 +1060,8 @@
1041
1060
  */
1042
1061
 
1043
1062
  /**
1044
- * @@@
1063
+ * Locates the LibreOffice executable on the current system by searching platform-specific paths.
1064
+ * Returns the path to the executable if found, or null otherwise.
1045
1065
  *
1046
1066
  * @private within the repository
1047
1067
  */
@@ -1059,7 +1079,8 @@
1059
1079
  */
1060
1080
 
1061
1081
  /**
1062
- * @@@
1082
+ * Locates the Pandoc executable on the current system by searching platform-specific paths.
1083
+ * Returns the path to the executable if found, or null otherwise.
1063
1084
  *
1064
1085
  * @private within the repository
1065
1086
  */
@@ -1077,7 +1098,7 @@
1077
1098
  */
1078
1099
 
1079
1100
  /**
1080
- * @@@
1101
+ * Provides paths to required executables (i.e. as Pandoc and LibreOffice) for Node.js environments.
1081
1102
  *
1082
1103
  * @public exported from `@promptbook/node`
1083
1104
  */
@@ -1277,8 +1298,12 @@
1277
1298
  */
1278
1299
 
1279
1300
  /**
1280
- * @@@
1301
+ * Creates a deep clone of the given object
1302
+ *
1303
+ * Note: This method only works for objects that are fully serializable to JSON and do not contain functions, Dates, or special types.
1281
1304
  *
1305
+ * @param objectValue The object to clone.
1306
+ * @returns A deep, writable clone of the input object.
1282
1307
  * @public exported from `@promptbook/utils`
1283
1308
  */
1284
1309
  function deepClone(objectValue) {
@@ -1360,13 +1385,13 @@
1360
1385
  */
1361
1386
  const REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
1362
1387
  /**
1363
- * @@@
1388
+ * Placeholder value indicating a parameter is missing its value.
1364
1389
  *
1365
1390
  * @private within the repository
1366
1391
  */
1367
1392
  const RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
1368
1393
  /**
1369
- * @@@
1394
+ * Placeholder value indicating a parameter is restricted and cannot be used directly.
1370
1395
  *
1371
1396
  * @private within the repository
1372
1397
  */
@@ -1398,7 +1423,7 @@
1398
1423
  /**
1399
1424
  * Tests if given string is valid semantic version
1400
1425
  *
1401
- * Note: There are two simmilar functions:
1426
+ * Note: There are two similar functions:
1402
1427
  * - `isValidSemanticVersion` which tests any semantic version
1403
1428
  * - `isValidPromptbookVersion` *(this one)* which tests just Promptbook versions
1404
1429
  *
@@ -1420,7 +1445,7 @@
1420
1445
  *
1421
1446
  * @see https://www.npmjs.com/package/promptbook?activeTab=versions
1422
1447
  * 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.
1423
- * Note: There are two simmilar functions:
1448
+ * Note: There are two similar functions:
1424
1449
  * - `isValidSemanticVersion` which tests any semantic version
1425
1450
  * - `isValidPromptbookVersion` *(this one)* which tests just Promptbook versions
1426
1451
  *
@@ -1441,7 +1466,7 @@
1441
1466
  * Tests if given string is valid URL.
1442
1467
  *
1443
1468
  * Note: Dataurl are considered perfectly valid.
1444
- * Note: There are two simmilar functions:
1469
+ * Note: There are two similar functions:
1445
1470
  * - `isValidUrl` which tests any URL
1446
1471
  * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1447
1472
  *
@@ -1469,7 +1494,7 @@
1469
1494
  /**
1470
1495
  * Tests if given string is valid pipeline URL URL.
1471
1496
  *
1472
- * Note: There are two simmilar functions:
1497
+ * Note: There are two similar functions:
1473
1498
  * - `isValidUrl` which tests any URL
1474
1499
  * - `isValidPipelineUrl` *(this one)* which tests just pipeline URL
1475
1500
  *
@@ -1566,7 +1591,7 @@
1566
1591
  ${block(pipelineIdentification)}
1567
1592
  `));
1568
1593
  }
1569
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1594
+ // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
1570
1595
  if (!Array.isArray(pipeline.parameters)) {
1571
1596
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1572
1597
  throw new ParseError(spaceTrim.spaceTrim((block) => `
@@ -1577,7 +1602,7 @@
1577
1602
  ${block(pipelineIdentification)}
1578
1603
  `));
1579
1604
  }
1580
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1605
+ // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
1581
1606
  if (!Array.isArray(pipeline.tasks)) {
1582
1607
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1583
1608
  throw new ParseError(spaceTrim.spaceTrim((block) => `
@@ -1797,15 +1822,18 @@
1797
1822
  * @public exported from `@promptbook/core`
1798
1823
  */
1799
1824
  function isPipelinePrepared(pipeline) {
1800
- // Note: Ignoring `pipeline.preparations` @@@
1801
- // Note: Ignoring `pipeline.knowledgePieces` @@@
1825
+ // Note: Ignoring `pipeline.preparations`
1826
+ // Note: Ignoring `pipeline.knowledgePieces`
1802
1827
  if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1828
+ // console.log('Pipeline is not prepared because title is undefined or empty', pipeline);
1803
1829
  return false;
1804
1830
  }
1805
1831
  if (!pipeline.personas.every((persona) => persona.modelsRequirements !== undefined)) {
1832
+ // console.log('Pipeline is not prepared because personas are not prepared', pipeline.personas);
1806
1833
  return false;
1807
1834
  }
1808
1835
  if (!pipeline.knowledgeSources.every((knowledgeSource) => knowledgeSource.preparationIds !== undefined)) {
1836
+ //console.log('Pipeline is not prepared because knowledge sources are not prepared', pipeline.knowledgeSources);
1809
1837
  return false;
1810
1838
  }
1811
1839
  /*
@@ -1830,7 +1858,7 @@
1830
1858
  * Function isValidJsonString will tell you if the string is valid JSON or not
1831
1859
  *
1832
1860
  * @param value The string to check
1833
- * @returns True if the string is a valid JSON string, false otherwise
1861
+ * @returns `true` if the string is a valid JSON string, false otherwise
1834
1862
  *
1835
1863
  * @public exported from `@promptbook/utils`
1836
1864
  */
@@ -1877,15 +1905,12 @@
1877
1905
  }
1878
1906
  throw new Error(spaceTrim__default["default"]((block) => `
1879
1907
  ${block(error.message)}
1880
-
1908
+
1881
1909
  The JSON text:
1882
1910
  ${block(value)}
1883
1911
  `));
1884
1912
  }
1885
1913
  }
1886
- /**
1887
- * TODO: !!!! Use in Promptbook.studio
1888
- */
1889
1914
 
1890
1915
  /**
1891
1916
  * Recursively converts JSON strings to JSON objects
@@ -1991,8 +2016,9 @@
1991
2016
  */
1992
2017
  function createTask(options) {
1993
2018
  const { taskType, taskProcessCallback } = options;
2019
+ let { title } = options;
1994
2020
  // TODO: [🐙] DRY
1995
- const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid simmilar char conflicts */)}`;
2021
+ const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
1996
2022
  let status = 'RUNNING';
1997
2023
  const createdAt = new Date();
1998
2024
  let updatedAt = createdAt;
@@ -2002,6 +2028,10 @@
2002
2028
  const partialResultSubject = new rxjs.Subject();
2003
2029
  // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
2004
2030
  const finalResultPromise = /* not await */ taskProcessCallback((newOngoingResult) => {
2031
+ if (newOngoingResult.title) {
2032
+ title = newOngoingResult.title;
2033
+ }
2034
+ updatedAt = new Date();
2005
2035
  Object.assign(currentValue, newOngoingResult);
2006
2036
  // <- TODO: assign deep
2007
2037
  partialResultSubject.next(newOngoingResult);
@@ -2047,17 +2077,24 @@
2047
2077
  return {
2048
2078
  taskType,
2049
2079
  taskId,
2080
+ get promptbookVersion() {
2081
+ return PROMPTBOOK_ENGINE_VERSION;
2082
+ },
2083
+ get title() {
2084
+ return title;
2085
+ // <- Note: [1] These must be getters to allow changing the value in the future
2086
+ },
2050
2087
  get status() {
2051
2088
  return status;
2052
- // <- Note: [1] Theese must be getters to allow changing the value in the future
2089
+ // <- Note: [1] --||--
2053
2090
  },
2054
2091
  get createdAt() {
2055
2092
  return createdAt;
2056
- // <- Note: [1]
2093
+ // <- Note: [1] --||--
2057
2094
  },
2058
2095
  get updatedAt() {
2059
2096
  return updatedAt;
2060
- // <- Note: [1]
2097
+ // <- Note: [1] --||--
2061
2098
  },
2062
2099
  asPromise,
2063
2100
  asObservable() {
@@ -2065,15 +2102,15 @@
2065
2102
  },
2066
2103
  get errors() {
2067
2104
  return errors;
2068
- // <- Note: [1]
2105
+ // <- Note: [1] --||--
2069
2106
  },
2070
2107
  get warnings() {
2071
2108
  return warnings;
2072
- // <- Note: [1]
2109
+ // <- Note: [1] --||--
2073
2110
  },
2074
2111
  get currentValue() {
2075
2112
  return currentValue;
2076
- // <- Note: [1]
2113
+ // <- Note: [1] --||--
2077
2114
  },
2078
2115
  };
2079
2116
  }
@@ -2082,6 +2119,74 @@
2082
2119
  * TODO: [🐚] Split into more files and make `PrepareTask` & `RemoteTask` + split the function
2083
2120
  */
2084
2121
 
2122
+ /**
2123
+ * Represents the uncertain value
2124
+ *
2125
+ * @public exported from `@promptbook/core`
2126
+ */
2127
+ const ZERO_VALUE = $deepFreeze({ value: 0 });
2128
+ /**
2129
+ * Represents the uncertain value
2130
+ *
2131
+ * @public exported from `@promptbook/core`
2132
+ */
2133
+ const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
2134
+ /**
2135
+ * Represents the usage with no resources consumed
2136
+ *
2137
+ * @public exported from `@promptbook/core`
2138
+ */
2139
+ const ZERO_USAGE = $deepFreeze({
2140
+ price: ZERO_VALUE,
2141
+ input: {
2142
+ tokensCount: ZERO_VALUE,
2143
+ charactersCount: ZERO_VALUE,
2144
+ wordsCount: ZERO_VALUE,
2145
+ sentencesCount: ZERO_VALUE,
2146
+ linesCount: ZERO_VALUE,
2147
+ paragraphsCount: ZERO_VALUE,
2148
+ pagesCount: ZERO_VALUE,
2149
+ },
2150
+ output: {
2151
+ tokensCount: ZERO_VALUE,
2152
+ charactersCount: ZERO_VALUE,
2153
+ wordsCount: ZERO_VALUE,
2154
+ sentencesCount: ZERO_VALUE,
2155
+ linesCount: ZERO_VALUE,
2156
+ paragraphsCount: ZERO_VALUE,
2157
+ pagesCount: ZERO_VALUE,
2158
+ },
2159
+ });
2160
+ /**
2161
+ * Represents the usage with unknown resources consumed
2162
+ *
2163
+ * @public exported from `@promptbook/core`
2164
+ */
2165
+ const UNCERTAIN_USAGE = $deepFreeze({
2166
+ price: UNCERTAIN_ZERO_VALUE,
2167
+ input: {
2168
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2169
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2170
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2171
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2172
+ linesCount: UNCERTAIN_ZERO_VALUE,
2173
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2174
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2175
+ },
2176
+ output: {
2177
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2178
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2179
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2180
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2181
+ linesCount: UNCERTAIN_ZERO_VALUE,
2182
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2183
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2184
+ },
2185
+ });
2186
+ /**
2187
+ * Note: [💞] Ignore a discrepancy between file name and entity name
2188
+ */
2189
+
2085
2190
  var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book",formfactorName:"GENERIC",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge from Markdown\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book`\n- INPUT PARAMETER `{knowledgeContent}` Markdown document content\n- OUTPUT PARAMETER `{knowledgePieces}` The knowledge JSON object\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}\n```\n\n`-> {knowledgePieces}`\n"}],sourceFile:"./books/prepare-knowledge-from-markdown.book"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.book",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Keywords\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-keywords.book`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{keywords}` Keywords separated by comma\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}\n```\n\n`-> {keywords}`\n"}],sourceFile:"./books/prepare-knowledge-keywords.book"},{title:"Prepare Knowledge-piece Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.book",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge-piece Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-title.book`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{title}` The title of the document\n\n## Knowledge\n\n- EXPECT MIN 1 WORD\n- EXPECT MAX 8 WORDS\n\n```markdown\nYou are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-knowledge-title.book"},{title:"Prepare Persona",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.book",formfactorName:"GENERIC",parameters:[{name:"availableModels",description:"List of available model names together with their descriptions as JSON",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelsRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-model-requirements",title:"Make modelRequirements",content:"You are an experienced AI engineer, you need to find the best models for virtual assistants:\n\n## Example\n\n```json\n[\n {\n \"modelName\": \"gpt-4o\",\n \"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n \"temperature\": 0.7\n },\n {\n \"modelName\": \"claude-3-5-sonnet\",\n \"systemMessage\": \"You are a friendly and knowledgeable chatbot.\",\n \"temperature\": 0.5\n }\n]\n```\n\n## Instructions\n\n- Your output format is JSON array\n- Sort best-fitting models first\n- Omit any models that are not suitable\n- Write just the JSON, no other text should be present\n- Array contain items with following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nHere are the available models:\n\n```json\n{availableModels}\n```\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelsRequirements",format:"JSON",dependentParameterNames:["availableModels","personaDescription"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Persona\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-persona.book`\n- INPUT PARAMETER `{availableModels}` List of available model names together with their descriptions as JSON\n- INPUT PARAMETER `{personaDescription}` Description of the persona\n- OUTPUT PARAMETER `{modelsRequirements}` Specific requirements for the model\n\n## Make modelRequirements\n\n- FORMAT JSON\n\n```markdown\nYou are an experienced AI engineer, you need to find the best models for virtual assistants:\n\n## Example\n\n\\`\\`\\`json\n[\n {\n \"modelName\": \"gpt-4o\",\n \"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n \"temperature\": 0.7\n },\n {\n \"modelName\": \"claude-3-5-sonnet\",\n \"systemMessage\": \"You are a friendly and knowledgeable chatbot.\",\n \"temperature\": 0.5\n }\n]\n\\`\\`\\`\n\n## Instructions\n\n- Your output format is JSON array\n- Sort best-fitting models first\n- Omit any models that are not suitable\n- Write just the JSON, no other text should be present\n- Array contain items with following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nHere are the available models:\n\n\\`\\`\\`json\n{availableModels}\n\\`\\`\\`\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}\n```\n\n`-> {modelsRequirements}`\n"}],sourceFile:"./books/prepare-persona.book"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-title.book",formfactorName:"GENERIC",parameters:[{name:"book",description:"The book to prepare the title for",isInput:true,isOutput:false},{name:"title",description:"Best title for the book",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-title",title:"Make title",content:"Make best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}",resultingParameterName:"title",expectations:{words:{min:1,max:8},lines:{min:1,max:1}},dependentParameterNames:["book"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-title.book`\n- INPUT PARAMETER `{book}` The book to prepare the title for\n- OUTPUT PARAMETER `{title}` Best title for the book\n\n## Make title\n\n- EXPECT MIN 1 Word\n- EXPECT MAX 8 Words\n- EXPECT EXACTLY 1 Line\n\n```markdown\nMake best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-title.book"}];
2086
2191
 
2087
2192
  /**
@@ -2242,7 +2347,7 @@
2242
2347
  if (bookVersion !== `undefined`) {
2243
2348
  commands.push(`BOOK VERSION ${bookVersion}`);
2244
2349
  }
2245
- // TODO: [main] !!5 This increases size of the bundle and is probbably not necessary
2350
+ // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
2246
2351
  pipelineString = prettifyMarkdown(pipelineString);
2247
2352
  for (const parameter of parameters.filter(({ isInput }) => isInput)) {
2248
2353
  commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
@@ -2426,7 +2531,7 @@
2426
2531
  /**
2427
2532
  * Constructs a pipeline collection from pipelines
2428
2533
  *
2429
- * @param pipelines @@@
2534
+ * @param pipelines Array of pipeline JSON objects to include in the collection
2430
2535
  *
2431
2536
  * Note: During the construction logic of all pipelines are validated
2432
2537
  * Note: It is not recommended to use this constructor directly, use `createCollectionFromJson` *(or other variant)* instead
@@ -2559,74 +2664,6 @@
2559
2664
  await Promise.all(tasks);
2560
2665
  }
2561
2666
 
2562
- /**
2563
- * Represents the uncertain value
2564
- *
2565
- * @public exported from `@promptbook/core`
2566
- */
2567
- const ZERO_VALUE = $deepFreeze({ value: 0 });
2568
- /**
2569
- * Represents the uncertain value
2570
- *
2571
- * @public exported from `@promptbook/core`
2572
- */
2573
- const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
2574
- /**
2575
- * Represents the usage with no resources consumed
2576
- *
2577
- * @public exported from `@promptbook/core`
2578
- */
2579
- const ZERO_USAGE = $deepFreeze({
2580
- price: ZERO_VALUE,
2581
- input: {
2582
- tokensCount: ZERO_VALUE,
2583
- charactersCount: ZERO_VALUE,
2584
- wordsCount: ZERO_VALUE,
2585
- sentencesCount: ZERO_VALUE,
2586
- linesCount: ZERO_VALUE,
2587
- paragraphsCount: ZERO_VALUE,
2588
- pagesCount: ZERO_VALUE,
2589
- },
2590
- output: {
2591
- tokensCount: ZERO_VALUE,
2592
- charactersCount: ZERO_VALUE,
2593
- wordsCount: ZERO_VALUE,
2594
- sentencesCount: ZERO_VALUE,
2595
- linesCount: ZERO_VALUE,
2596
- paragraphsCount: ZERO_VALUE,
2597
- pagesCount: ZERO_VALUE,
2598
- },
2599
- });
2600
- /**
2601
- * Represents the usage with unknown resources consumed
2602
- *
2603
- * @public exported from `@promptbook/core`
2604
- */
2605
- $deepFreeze({
2606
- price: UNCERTAIN_ZERO_VALUE,
2607
- input: {
2608
- tokensCount: UNCERTAIN_ZERO_VALUE,
2609
- charactersCount: UNCERTAIN_ZERO_VALUE,
2610
- wordsCount: UNCERTAIN_ZERO_VALUE,
2611
- sentencesCount: UNCERTAIN_ZERO_VALUE,
2612
- linesCount: UNCERTAIN_ZERO_VALUE,
2613
- paragraphsCount: UNCERTAIN_ZERO_VALUE,
2614
- pagesCount: UNCERTAIN_ZERO_VALUE,
2615
- },
2616
- output: {
2617
- tokensCount: UNCERTAIN_ZERO_VALUE,
2618
- charactersCount: UNCERTAIN_ZERO_VALUE,
2619
- wordsCount: UNCERTAIN_ZERO_VALUE,
2620
- sentencesCount: UNCERTAIN_ZERO_VALUE,
2621
- linesCount: UNCERTAIN_ZERO_VALUE,
2622
- paragraphsCount: UNCERTAIN_ZERO_VALUE,
2623
- pagesCount: UNCERTAIN_ZERO_VALUE,
2624
- },
2625
- });
2626
- /**
2627
- * Note: [💞] Ignore a discrepancy between file name and entity name
2628
- */
2629
-
2630
2667
  /**
2631
2668
  * Function `addUsage` will add multiple usages into one
2632
2669
  *
@@ -2686,12 +2723,14 @@
2686
2723
  const spending = new rxjs.Subject();
2687
2724
  const proxyTools = {
2688
2725
  get title() {
2689
- // TODO: [🧠] Maybe put here some suffix
2690
- return llmTools.title;
2726
+ return `${llmTools.title} (+usage)`;
2727
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
2728
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(+usage)"?
2691
2729
  },
2692
2730
  get description() {
2693
- // TODO: [🧠] Maybe put here some suffix
2694
- return llmTools.description;
2731
+ return `${llmTools.description} (+usage)`;
2732
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
2733
+ // <- TODO: [🧈][🧠] Does it make sence to suffix "(+usage)"?
2695
2734
  },
2696
2735
  checkConfiguration() {
2697
2736
  return /* not await */ llmTools.checkConfiguration();
@@ -2762,29 +2801,40 @@
2762
2801
  return 'Multiple LLM Providers';
2763
2802
  }
2764
2803
  get description() {
2765
- return this.llmExecutionTools.map(({ title }, index) => `${index + 1}) \`${title}\``).join('\n');
2804
+ const innerModelsTitlesAndDescriptions = this.llmExecutionTools
2805
+ .map(({ title, description }, index) => {
2806
+ const headLine = `${index + 1}) \`${title}\``;
2807
+ if (description === undefined) {
2808
+ return headLine;
2809
+ }
2810
+ return spaceTrim__default["default"]((block) => `
2811
+ ${headLine}
2812
+
2813
+ ${ /* <- Note: Indenting the description: */block(description)}
2814
+ `);
2815
+ })
2816
+ .join('\n\n');
2817
+ return spaceTrim__default["default"]((block) => `
2818
+ Multiple LLM Providers:
2819
+
2820
+ ${block(innerModelsTitlesAndDescriptions)}
2821
+ `);
2766
2822
  }
2767
2823
  /**
2768
2824
  * Check the configuration of all execution tools
2769
2825
  */
2770
2826
  async checkConfiguration() {
2771
- // TODO: Maybe do it in parallel
2772
- for (const llmExecutionTools of this.llmExecutionTools) {
2773
- await llmExecutionTools.checkConfiguration();
2774
- }
2827
+ // Note: Run checks in parallel
2828
+ await Promise.all(this.llmExecutionTools.map((tools) => tools.checkConfiguration()));
2775
2829
  }
2776
2830
  /**
2777
2831
  * List all available models that can be used
2778
2832
  * This lists is a combination of all available models from all execution tools
2779
2833
  */
2780
2834
  async listModels() {
2781
- const availableModels = [];
2782
- for (const llmExecutionTools of this.llmExecutionTools) {
2783
- // TODO: [🪂] Obtain models in parallel
2784
- const models = await llmExecutionTools.listModels();
2785
- availableModels.push(...models);
2786
- }
2787
- return availableModels;
2835
+ // Obtain all models in parallel and flatten
2836
+ const modelArrays = await Promise.all(this.llmExecutionTools.map((tools) => tools.listModels()));
2837
+ return modelArrays.flat();
2788
2838
  }
2789
2839
  /**
2790
2840
  * Calls the best available chat model
@@ -3025,7 +3075,8 @@
3025
3075
  */
3026
3076
 
3027
3077
  /**
3028
- * @@@
3078
+ * Safely retrieves the global scope object (window in browser, global in Node.js)
3079
+ * regardless of the JavaScript environment in which the code is running
3029
3080
  *
3030
3081
  * Note: `$` is used to indicate that this function is not a pure function - it access global scope
3031
3082
  *
@@ -3036,10 +3087,10 @@
3036
3087
  }
3037
3088
 
3038
3089
  /**
3039
- * @@@
3090
+ * Normalizes a text string to SCREAMING_CASE (all uppercase with underscores).
3040
3091
  *
3041
- * @param text @@@
3042
- * @returns @@@
3092
+ * @param text The text string to be converted to SCREAMING_CASE format.
3093
+ * @returns The normalized text in SCREAMING_CASE format.
3043
3094
  * @example 'HELLO_WORLD'
3044
3095
  * @example 'I_LOVE_PROMPTBOOK'
3045
3096
  * @public exported from `@promptbook/utils`
@@ -3091,10 +3142,10 @@
3091
3142
  */
3092
3143
 
3093
3144
  /**
3094
- * @@@
3145
+ * Normalizes a text string to snake_case format.
3095
3146
  *
3096
- * @param text @@@
3097
- * @returns @@@
3147
+ * @param text The text string to be converted to snake_case format.
3148
+ * @returns The normalized text in snake_case format.
3098
3149
  * @example 'hello_world'
3099
3150
  * @example 'i_love_promptbook'
3100
3151
  * @public exported from `@promptbook/utils`
@@ -3104,11 +3155,11 @@
3104
3155
  }
3105
3156
 
3106
3157
  /**
3107
- * Register is @@@
3158
+ * Global registry for storing and managing registered entities of a given type.
3108
3159
  *
3109
3160
  * Note: `$` is used to indicate that this function is not a pure function - it accesses and adds variables in global scope.
3110
3161
  *
3111
- * @private internal utility, exported are only signleton instances of this class
3162
+ * @private internal utility, exported are only singleton instances of this class
3112
3163
  */
3113
3164
  class $Register {
3114
3165
  constructor(registerName) {
@@ -3152,10 +3203,10 @@
3152
3203
  }
3153
3204
 
3154
3205
  /**
3155
- * @@@
3206
+ * Global registry for storing metadata about all available scrapers and converters.
3156
3207
  *
3157
- * Note: `$` is used to indicate that this interacts with the global scope
3158
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
3208
+ * Note: `$` is used to indicate that this interacts with the global scope.
3209
+ * @singleton Only one instance of each register is created per build, but there can be more in different contexts (e.g., tests).
3159
3210
  * @public exported from `@promptbook/core`
3160
3211
  */
3161
3212
  const $scrapersMetadataRegister = new $Register('scrapers_metadata');
@@ -3164,10 +3215,11 @@
3164
3215
  */
3165
3216
 
3166
3217
  /**
3167
- * @@@
3218
+ * Registry for all available scrapers in the system.
3219
+ * Central point for registering and accessing different types of content scrapers.
3168
3220
  *
3169
3221
  * Note: `$` is used to indicate that this interacts with the global scope
3170
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
3222
+ * @singleton Only one instance of each register is created per build, but there can be more than one in different build modules
3171
3223
  * @public exported from `@promptbook/core`
3172
3224
  */
3173
3225
  const $scrapersRegister = new $Register('scraper_constructors');
@@ -3507,10 +3559,10 @@
3507
3559
  */
3508
3560
 
3509
3561
  /**
3510
- * @@@
3562
+ * Removes diacritic marks (accents) from characters in a string.
3511
3563
  *
3512
- * @param input @@@
3513
- * @returns @@@
3564
+ * @param input The string containing diacritics to be normalized.
3565
+ * @returns The string with diacritics removed or normalized.
3514
3566
  * @public exported from `@promptbook/utils`
3515
3567
  */
3516
3568
  function removeDiacritics(input) {
@@ -3524,10 +3576,10 @@
3524
3576
  */
3525
3577
 
3526
3578
  /**
3527
- * @@@
3579
+ * Converts a given text to kebab-case format.
3528
3580
  *
3529
- * @param text @@@
3530
- * @returns @@@
3581
+ * @param text The text to be converted.
3582
+ * @returns The kebab-case formatted string.
3531
3583
  * @example 'hello-world'
3532
3584
  * @example 'i-love-promptbook'
3533
3585
  * @public exported from `@promptbook/utils`
@@ -3596,7 +3648,8 @@
3596
3648
  */
3597
3649
 
3598
3650
  /**
3599
- * @@@
3651
+ * Converts a name to a properly formatted subfolder path for cache storage.
3652
+ * Handles normalization and path formatting to create consistent cache directory structures.
3600
3653
  *
3601
3654
  * @private for `FileCacheStorage`
3602
3655
  */
@@ -3676,11 +3729,11 @@
3676
3729
  }
3677
3730
 
3678
3731
  /**
3679
- * @@@
3732
+ * Converts a title string into a normalized name.
3680
3733
  *
3681
- * @param value @@@
3682
- * @returns @@@
3683
- * @example @@@
3734
+ * @param value The title string to be converted to a name.
3735
+ * @returns A normalized name derived from the input title.
3736
+ * @example 'Hello World!' -> 'hello-world'
3684
3737
  * @public exported from `@promptbook/utils`
3685
3738
  */
3686
3739
  function titleToName(value) {
@@ -3731,7 +3784,9 @@
3731
3784
  */
3732
3785
 
3733
3786
  /**
3734
- * @@@
3787
+ * Factory function that creates a handler for processing knowledge sources.
3788
+ * Provides standardized processing of different types of knowledge sources
3789
+ * across various scraper implementations.
3735
3790
  *
3736
3791
  * @public exported from `@promptbook/core`
3737
3792
  */
@@ -3870,7 +3925,7 @@
3870
3925
  }
3871
3926
 
3872
3927
  /**
3873
- * Prepares the knowle
3928
+ * Prepares the knowledge pieces
3874
3929
  *
3875
3930
  * @see https://github.com/webgptorg/promptbook/discussions/41
3876
3931
  * @public exported from `@promptbook/core`
@@ -3966,15 +4021,18 @@
3966
4021
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
3967
4022
  * Put `knowledgePieces` into `PrepareKnowledgeOptions`
3968
4023
  * TODO: [🪂] More than max things can run in parallel by acident [1,[2a,2b,_],[3a,3b,_]]
3969
- * TODO: [🧠][❎] Do here propper M:N mapping
4024
+ * TODO: [🧠][❎] Do here proper M:N mapping
3970
4025
  * [x] One source can make multiple pieces
3971
4026
  * [ ] One piece can have multiple sources
3972
4027
  */
3973
4028
 
3974
4029
  /**
3975
- * @@@
4030
+ * Prepares tasks by adding knowledge to the prompt and ensuring all necessary parameters are included.
3976
4031
  *
3977
- * @public exported from `@promptbook/core`
4032
+ * @param tasks Sequence of tasks that are chained together to form a pipeline
4033
+ * @returns A promise that resolves to the prepared tasks.
4034
+ *
4035
+ * @private internal utility of `preparePipeline`
3978
4036
  */
3979
4037
  async function prepareTasks(pipeline, tools, options) {
3980
4038
  const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT } = options;
@@ -4012,7 +4070,7 @@
4012
4070
  return { tasksPrepared };
4013
4071
  }
4014
4072
  /**
4015
- * TODO: [😂] Adding knowledge should be convert to async high-level abstractions, simmilar thing with expectations to sync high-level abstractions
4073
+ * TODO: [😂] Adding knowledge should be convert to async high-level abstractions, similar thing with expectations to sync high-level abstractions
4016
4074
  * TODO: [🧠] Add context to each task (if missing)
4017
4075
  * TODO: [🧠] What is better name `prepareTask` or `prepareTaskAndParameters`
4018
4076
  * TODO: [♨][main] !!3 Prepare index the examples and maybe tasks
@@ -4148,7 +4206,7 @@
4148
4206
  order: ORDER_OF_PIPELINE_JSON,
4149
4207
  value: {
4150
4208
  ...pipeline,
4151
- // <- TODO: Probbably deeply clone the pipeline because `$exportJson` freezes the subobjects
4209
+ // <- TODO: Probably deeply clone the pipeline because `$exportJson` freezes the subobjects
4152
4210
  title,
4153
4211
  knowledgeSources: knowledgeSourcesPrepared,
4154
4212
  knowledgePieces: knowledgePiecesPrepared,
@@ -4411,7 +4469,7 @@
4411
4469
  }
4412
4470
 
4413
4471
  /**
4414
- * @@@
4472
+ * Contains configuration options for parsing and generating CSV files, such as delimiters and quoting rules.
4415
4473
  *
4416
4474
  * @public exported from `@promptbook/core`
4417
4475
  */
@@ -4420,11 +4478,29 @@
4420
4478
  // encoding: 'utf-8',
4421
4479
  });
4422
4480
 
4481
+ /**
4482
+ * Converts a CSV string into an object
4483
+ *
4484
+ * Note: This is wrapper around `papaparse.parse()` with better autohealing
4485
+ *
4486
+ * @private - for now until `@promptbook/csv` is released
4487
+ */
4488
+ function csvParse(value /* <- TODO: string_csv */, settings, schema /* <- TODO: Make CSV Schemas */) {
4489
+ settings = { ...settings, ...MANDATORY_CSV_SETTINGS };
4490
+ // Note: Autoheal invalid '\n' characters
4491
+ if (settings.newline && !settings.newline.includes('\r') && value.includes('\r')) {
4492
+ console.warn('CSV string contains carriage return characters, but in the CSV settings the `newline` setting does not include them. Autohealing the CSV string.');
4493
+ value = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
4494
+ }
4495
+ const csv = papaparse.parse(value, settings);
4496
+ return csv;
4497
+ }
4498
+
4423
4499
  /**
4424
4500
  * Function to check if a string is valid CSV
4425
4501
  *
4426
4502
  * @param value The string to check
4427
- * @returns True if the string is a valid CSV string, false otherwise
4503
+ * @returns `true` if the string is a valid CSV string, false otherwise
4428
4504
  *
4429
4505
  * @public exported from `@promptbook/utils`
4430
4506
  */
@@ -4448,7 +4524,7 @@
4448
4524
  * @public exported from `@promptbook/core`
4449
4525
  * <- TODO: [🏢] Export from package `@promptbook/csv`
4450
4526
  */
4451
- const CsvFormatDefinition = {
4527
+ const CsvFormatParser = {
4452
4528
  formatName: 'CSV',
4453
4529
  aliases: ['SPREADSHEET', 'TABLE'],
4454
4530
  isValid(value, settings, schema) {
@@ -4460,12 +4536,12 @@
4460
4536
  heal(value, settings, schema) {
4461
4537
  throw new Error('Not implemented');
4462
4538
  },
4463
- subvalueDefinitions: [
4539
+ subvalueParsers: [
4464
4540
  {
4465
4541
  subvalueName: 'ROW',
4466
- async mapValues(value, outputParameterName, settings, mapCallback) {
4467
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
4468
- const csv = papaparse.parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
4542
+ async mapValues(options) {
4543
+ const { value, outputParameterName, settings, mapCallback, onProgress } = options;
4544
+ const csv = csvParse(value, settings);
4469
4545
  if (csv.errors.length !== 0) {
4470
4546
  throw new CsvFormatError(spaceTrim__default["default"]((block) => `
4471
4547
  CSV parsing error
@@ -4480,23 +4556,37 @@
4480
4556
  ${block(value)}
4481
4557
  `));
4482
4558
  }
4483
- const mappedData = await Promise.all(csv.data.map(async (row, index) => {
4559
+ const mappedData = [];
4560
+ const length = csv.data.length;
4561
+ for (let index = 0; index < length; index++) {
4562
+ const row = csv.data[index];
4484
4563
  if (row[outputParameterName]) {
4485
4564
  throw new CsvFormatError(`Can not overwrite existing column "${outputParameterName}" in CSV row`);
4486
4565
  }
4487
- return {
4566
+ const mappedRow = {
4488
4567
  ...row,
4489
- [outputParameterName]: await mapCallback(row, index),
4568
+ [outputParameterName]: await mapCallback(row, index, length),
4490
4569
  };
4491
- }));
4570
+ mappedData.push(mappedRow);
4571
+ if (onProgress) {
4572
+ // Note: Report the CSV with all rows mapped so far
4573
+ /*
4574
+ // TODO: [🛕] Report progress with all the rows including the pending ones
4575
+ const progressData = mappedData.map((row, i) =>
4576
+ i > index ? { ...row, [outputParameterName]: PENDING_VALUE_PLACEHOLDER } : row,
4577
+ );
4578
+ */
4579
+ await onProgress(papaparse.unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS }));
4580
+ }
4581
+ }
4492
4582
  return papaparse.unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS });
4493
4583
  },
4494
4584
  },
4495
4585
  {
4496
4586
  subvalueName: 'CELL',
4497
- async mapValues(value, outputParameterName, settings, mapCallback) {
4498
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
4499
- const csv = papaparse.parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
4587
+ async mapValues(options) {
4588
+ const { value, settings, mapCallback, onProgress } = options;
4589
+ const csv = csvParse(value, settings);
4500
4590
  if (csv.errors.length !== 0) {
4501
4591
  throw new CsvFormatError(spaceTrim__default["default"]((block) => `
4502
4592
  CSV parsing error
@@ -4512,9 +4602,9 @@
4512
4602
  `));
4513
4603
  }
4514
4604
  const mappedData = await Promise.all(csv.data.map(async (row, rowIndex) => {
4515
- return /* not await */ Promise.all(Object.entries(row).map(async ([key, value], columnIndex) => {
4605
+ return /* not await */ Promise.all(Object.entries(row).map(async ([key, value], columnIndex, array) => {
4516
4606
  const index = rowIndex * Object.keys(row).length + columnIndex;
4517
- return /* not await */ mapCallback({ [key]: value }, index);
4607
+ return /* not await */ mapCallback({ [key]: value }, index, array.length);
4518
4608
  }));
4519
4609
  }));
4520
4610
  return papaparse.unparse(mappedData, { ...settings, ...MANDATORY_CSV_SETTINGS });
@@ -4523,10 +4613,10 @@
4523
4613
  ],
4524
4614
  };
4525
4615
  /**
4526
- * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
4527
- * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
4528
- * TODO: [🍓] In `CsvFormatDefinition` implement `heal
4529
- * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
4616
+ * TODO: [🍓] In `CsvFormatParser` implement simple `isValid`
4617
+ * TODO: [🍓] In `CsvFormatParser` implement partial `canBeValid`
4618
+ * TODO: [🍓] In `CsvFormatParser` implement `heal
4619
+ * TODO: [🍓] In `CsvFormatParser` implement `subvalueParsers`
4530
4620
  * TODO: [🏢] Allow to expect something inside CSV objects and other formats
4531
4621
  */
4532
4622
 
@@ -4535,7 +4625,7 @@
4535
4625
  *
4536
4626
  * @private still in development [🏢]
4537
4627
  */
4538
- const JsonFormatDefinition = {
4628
+ const JsonFormatParser = {
4539
4629
  formatName: 'JSON',
4540
4630
  mimeType: 'application/json',
4541
4631
  isValid(value, settings, schema) {
@@ -4547,28 +4637,28 @@
4547
4637
  heal(value, settings, schema) {
4548
4638
  throw new Error('Not implemented');
4549
4639
  },
4550
- subvalueDefinitions: [],
4640
+ subvalueParsers: [],
4551
4641
  };
4552
4642
  /**
4553
- * TODO: [🧠] Maybe propper instance of object
4643
+ * TODO: [🧠] Maybe proper instance of object
4554
4644
  * TODO: [0] Make string_serialized_json
4555
4645
  * TODO: [1] Make type for JSON Settings and Schema
4556
4646
  * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
4557
- * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
4558
- * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
4559
- * TODO: [🍓] In `JsonFormatDefinition` implement `heal
4560
- * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
4647
+ * TODO: [🍓] In `JsonFormatParser` implement simple `isValid`
4648
+ * TODO: [🍓] In `JsonFormatParser` implement partial `canBeValid`
4649
+ * TODO: [🍓] In `JsonFormatParser` implement `heal
4650
+ * TODO: [🍓] In `JsonFormatParser` implement `subvalueParsers`
4561
4651
  * TODO: [🏢] Allow to expect something inside JSON objects and other formats
4562
4652
  */
4563
4653
 
4564
4654
  /**
4565
4655
  * Definition for any text - this will be always valid
4566
4656
  *
4567
- * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
4657
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueParsers`
4568
4658
  *
4569
4659
  * @public exported from `@promptbook/core`
4570
4660
  */
4571
- const TextFormatDefinition = {
4661
+ const TextFormatParser = {
4572
4662
  formatName: 'TEXT',
4573
4663
  isValid(value) {
4574
4664
  return typeof value === 'string';
@@ -4577,19 +4667,20 @@
4577
4667
  return typeof partialValue === 'string';
4578
4668
  },
4579
4669
  heal() {
4580
- throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
4670
+ throw new UnexpectedError('It does not make sense to call `TextFormatParser.heal`');
4581
4671
  },
4582
- subvalueDefinitions: [
4672
+ subvalueParsers: [
4583
4673
  {
4584
4674
  subvalueName: 'LINE',
4585
- async mapValues(value, outputParameterName, settings, mapCallback) {
4675
+ async mapValues(options) {
4676
+ const { value, mapCallback, onProgress } = options;
4586
4677
  const lines = value.split('\n');
4587
- const mappedLines = await Promise.all(lines.map((lineContent, lineNumber) =>
4678
+ const mappedLines = await Promise.all(lines.map((lineContent, lineNumber, array) =>
4588
4679
  // TODO: [🧠] Maybe option to skip empty line
4589
4680
  /* not await */ mapCallback({
4590
4681
  lineContent,
4591
4682
  // TODO: [🧠] Maybe also put here `lineNumber`
4592
- }, lineNumber)));
4683
+ }, lineNumber, array.length)));
4593
4684
  return mappedLines.join('\n');
4594
4685
  },
4595
4686
  },
@@ -4599,10 +4690,10 @@
4599
4690
  /**
4600
4691
  * TODO: [1] Make type for XML Text and Schema
4601
4692
  * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages available as subvalues
4602
- * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
4603
- * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
4604
- * TODO: [🍓] In `TextFormatDefinition` implement `heal
4605
- * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
4693
+ * TODO: [🍓] In `TextFormatParser` implement simple `isValid`
4694
+ * TODO: [🍓] In `TextFormatParser` implement partial `canBeValid`
4695
+ * TODO: [🍓] In `TextFormatParser` implement `heal
4696
+ * TODO: [🍓] In `TextFormatParser` implement `subvalueParsers`
4606
4697
  * TODO: [🏢] Allow to expect something inside each item of list and other formats
4607
4698
  */
4608
4699
 
@@ -4610,7 +4701,7 @@
4610
4701
  * Function to check if a string is valid XML
4611
4702
  *
4612
4703
  * @param value
4613
- * @returns True if the string is a valid XML string, false otherwise
4704
+ * @returns `true` if the string is a valid XML string, false otherwise
4614
4705
  *
4615
4706
  * @public exported from `@promptbook/utils`
4616
4707
  */
@@ -4635,7 +4726,7 @@
4635
4726
  *
4636
4727
  * @private still in development [🏢]
4637
4728
  */
4638
- const XmlFormatDefinition = {
4729
+ const XmlFormatParser = {
4639
4730
  formatName: 'XML',
4640
4731
  mimeType: 'application/xml',
4641
4732
  isValid(value, settings, schema) {
@@ -4647,17 +4738,17 @@
4647
4738
  heal(value, settings, schema) {
4648
4739
  throw new Error('Not implemented');
4649
4740
  },
4650
- subvalueDefinitions: [],
4741
+ subvalueParsers: [],
4651
4742
  };
4652
4743
  /**
4653
- * TODO: [🧠] Maybe propper instance of object
4744
+ * TODO: [🧠] Maybe proper instance of object
4654
4745
  * TODO: [0] Make string_serialized_xml
4655
4746
  * TODO: [1] Make type for XML Settings and Schema
4656
4747
  * TODO: [🧠] What to use for validating XMLs - XSD,...
4657
- * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
4658
- * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
4659
- * TODO: [🍓] In `XmlFormatDefinition` implement `heal
4660
- * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
4748
+ * TODO: [🍓] In `XmlFormatParser` implement simple `isValid`
4749
+ * TODO: [🍓] In `XmlFormatParser` implement partial `canBeValid`
4750
+ * TODO: [🍓] In `XmlFormatParser` implement `heal
4751
+ * TODO: [🍓] In `XmlFormatParser` implement `subvalueParsers`
4661
4752
  * TODO: [🏢] Allow to expect something inside XML and other formats
4662
4753
  */
4663
4754
 
@@ -4666,24 +4757,19 @@
4666
4757
  *
4667
4758
  * @private internal index of `...` <- TODO [🏢]
4668
4759
  */
4669
- const FORMAT_DEFINITIONS = [
4670
- JsonFormatDefinition,
4671
- XmlFormatDefinition,
4672
- TextFormatDefinition,
4673
- CsvFormatDefinition,
4674
- ];
4760
+ const FORMAT_DEFINITIONS = [JsonFormatParser, XmlFormatParser, TextFormatParser, CsvFormatParser];
4675
4761
  /**
4676
4762
  * Note: [💞] Ignore a discrepancy between file name and entity name
4677
4763
  */
4678
4764
 
4679
4765
  /**
4680
- * Maps available parameters to expected parameters
4766
+ * Maps available parameters to expected parameters for a pipeline task.
4681
4767
  *
4682
4768
  * The strategy is:
4683
- * 1) @@@
4684
- * 2) @@@
4769
+ * 1) First, match parameters by name where both available and expected.
4770
+ * 2) Then, if there are unmatched expected and available parameters, map them by order.
4685
4771
  *
4686
- * @throws {PipelineExecutionError} @@@
4772
+ * @throws {PipelineExecutionError} If the number of unmatched expected and available parameters does not match, or mapping is ambiguous.
4687
4773
  * @private within the repository used in `createPipelineExecutor`
4688
4774
  */
4689
4775
  function mapAvailableToExpectedParameters(options) {
@@ -4706,7 +4792,7 @@
4706
4792
  else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) ;
4707
4793
  }
4708
4794
  if (expectedParameterNames.size === 0) {
4709
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
4795
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent accidental modifications after mapping
4710
4796
  Object.freeze(mappedParameters);
4711
4797
  return mappedParameters;
4712
4798
  }
@@ -4737,7 +4823,7 @@
4737
4823
  for (let i = 0; i < expectedParameterNames.size; i++) {
4738
4824
  mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
4739
4825
  }
4740
- // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
4826
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent accidental modifications after mapping
4741
4827
  Object.freeze(mappedParameters);
4742
4828
  return mappedParameters;
4743
4829
  }
@@ -4745,8 +4831,8 @@
4745
4831
  /**
4746
4832
  * Extracts all code blocks from markdown.
4747
4833
  *
4748
- * Note: There are multiple simmilar function:
4749
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
4834
+ * Note: There are multiple similar functions:
4835
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
4750
4836
  * - `extractJsonBlock` extracts exactly one valid JSON code block
4751
4837
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
4752
4838
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
@@ -4796,7 +4882,7 @@
4796
4882
  if (currentCodeBlock.content !== '') {
4797
4883
  currentCodeBlock.content += '\n';
4798
4884
  }
4799
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
4885
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make proper unescape */;
4800
4886
  }
4801
4887
  }
4802
4888
  if (currentCodeBlock !== null) {
@@ -4816,7 +4902,7 @@
4816
4902
  * - When there are multiple JSON code blocks the function throws a `ParseError`
4817
4903
  *
4818
4904
  * Note: It is not important if marked as ```json BUT if it is VALID JSON
4819
- * Note: There are multiple simmilar function:
4905
+ * Note: There are multiple similar function:
4820
4906
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
4821
4907
  * - `extractJsonBlock` extracts exactly one valid JSON code block
4822
4908
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
@@ -4841,14 +4927,14 @@
4841
4927
  }
4842
4928
  /**
4843
4929
  * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
4844
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
4930
+ * TODO: [🏢] Make this logic part of `JsonFormatParser` or `isValidJsonString`
4845
4931
  */
4846
4932
 
4847
4933
  /**
4848
4934
  * Just says that the variable is not used but should be kept
4849
4935
  * No side effects.
4850
4936
  *
4851
- * Note: It can be usefull for:
4937
+ * Note: It can be useful for:
4852
4938
  *
4853
4939
  * 1) Suppressing eager optimization of unused imports
4854
4940
  * 2) Suppressing eslint errors of unused variables in the tests
@@ -5060,14 +5146,14 @@
5060
5146
  PAGES: countPages,
5061
5147
  };
5062
5148
  /**
5063
- * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
5149
+ * TODO: [🧠][🤠] This should be probably as part of `TextFormatParser`
5064
5150
  * Note: [💞] Ignore a discrepancy between file name and entity name
5065
5151
  */
5066
5152
 
5067
5153
  /**
5068
5154
  * Function checkExpectations will check if the expectations on given value are met
5069
5155
  *
5070
- * Note: There are two simmilar functions:
5156
+ * Note: There are two similar functions:
5071
5157
  * - `checkExpectations` which throws an error if the expectations are not met
5072
5158
  * - `isPassingExpectations` which returns a boolean
5073
5159
  *
@@ -5088,13 +5174,17 @@
5088
5174
  }
5089
5175
  /**
5090
5176
  * TODO: [💝] Unite object for expecting amount and format
5091
- * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
5177
+ * TODO: [🧠][🤠] This should be part of `TextFormatParser`
5092
5178
  * Note: [💝] and [🤠] are interconnected together
5093
5179
  */
5094
5180
 
5095
5181
  /**
5096
- * @@@
5182
+ * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
5183
+ * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
5184
+ * Throws errors if execution fails after all attempts.
5097
5185
  *
5186
+ * @param options - The options for execution, including task, parameters, pipeline, and configuration.
5187
+ * @returns The result string of the executed task.
5098
5188
  * @private internal utility of `createPipelineExecutor`
5099
5189
  */
5100
5190
  async function executeAttempts(options) {
@@ -5316,7 +5406,7 @@
5316
5406
  if (task.format) {
5317
5407
  if (task.format === 'JSON') {
5318
5408
  if (!isValidJsonString($ongoingTaskResult.$resultString || '')) {
5319
- // TODO: [🏢] Do more universally via `FormatDefinition`
5409
+ // TODO: [🏢] Do more universally via `FormatParser`
5320
5410
  try {
5321
5411
  $ongoingTaskResult.$resultString = extractJsonBlock($ongoingTaskResult.$resultString || '');
5322
5412
  }
@@ -5418,12 +5508,16 @@
5418
5508
  */
5419
5509
 
5420
5510
  /**
5421
- * @@@
5511
+ * Executes a pipeline task that requires mapping or iterating over subvalues of a parameter (such as rows in a CSV).
5512
+ * Handles format and subformat resolution, error handling, and progress reporting.
5513
+ *
5514
+ * @param options - Options for execution, including task details and progress callback.
5515
+ * @returns The result of the subvalue mapping or execution attempts.
5422
5516
  *
5423
5517
  * @private internal utility of `createPipelineExecutor`
5424
5518
  */
5425
5519
  async function executeFormatSubvalues(options) {
5426
- const { task, jokerParameterNames, parameters, priority, csvSettings, pipelineIdentification } = options;
5520
+ const { task, jokerParameterNames, parameters, priority, csvSettings, onProgress, pipelineIdentification } = options;
5427
5521
  if (task.foreach === undefined) {
5428
5522
  return /* not await */ executeAttempts(options);
5429
5523
  }
@@ -5454,16 +5548,16 @@
5454
5548
  ${block(pipelineIdentification)}
5455
5549
  `));
5456
5550
  }
5457
- const subvalueDefinition = formatDefinition.subvalueDefinitions.find((subvalueDefinition) => [subvalueDefinition.subvalueName, ...(subvalueDefinition.aliases || [])].includes(task.foreach.subformatName));
5458
- if (subvalueDefinition === undefined) {
5551
+ const subvalueParser = formatDefinition.subvalueParsers.find((subvalueParser) => [subvalueParser.subvalueName, ...(subvalueParser.aliases || [])].includes(task.foreach.subformatName));
5552
+ if (subvalueParser === undefined) {
5459
5553
  throw new UnexpectedError(
5460
5554
  // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
5461
5555
  spaceTrim__default["default"]((block) => `
5462
5556
  Unsupported subformat name "${task.foreach.subformatName}" for format "${task.foreach.formatName}"
5463
5557
 
5464
5558
  Available subformat names for format "${formatDefinition.formatName}":
5465
- ${block(formatDefinition.subvalueDefinitions
5466
- .map((subvalueDefinition) => subvalueDefinition.subvalueName)
5559
+ ${block(formatDefinition.subvalueParsers
5560
+ .map((subvalueParser) => subvalueParser.subvalueName)
5467
5561
  .map((subvalueName) => `- ${subvalueName}`)
5468
5562
  .join('\n'))}
5469
5563
 
@@ -5475,55 +5569,85 @@
5475
5569
  let formatSettings;
5476
5570
  if (formatDefinition.formatName === 'CSV') {
5477
5571
  formatSettings = csvSettings;
5478
- // <- TODO: [🤹‍♂️] More universal, make simmilar pattern for other formats for example \n vs \r\n in text
5479
- }
5480
- const resultString = await subvalueDefinition.mapValues(parameterValue, task.foreach.outputSubparameterName, formatSettings, async (subparameters, index) => {
5481
- let mappedParameters;
5482
- // TODO: [🤹‍♂️][🪂] Limit to N concurrent executions
5483
- // TODO: When done [🐚] Report progress also for each subvalue here
5484
- try {
5485
- mappedParameters = mapAvailableToExpectedParameters({
5486
- expectedParameters: Object.fromEntries(task.foreach.inputSubparameterNames.map((subparameterName) => [subparameterName, null])),
5487
- availableParameters: subparameters,
5488
- });
5489
- }
5490
- catch (error) {
5491
- if (!(error instanceof PipelineExecutionError)) {
5492
- throw error;
5572
+ // <- TODO: [🤹‍♂️] More universal, make similar pattern for other formats for example \n vs \r\n in text
5573
+ }
5574
+ const resultString = await subvalueParser.mapValues({
5575
+ value: parameterValue,
5576
+ outputParameterName: task.foreach.outputSubparameterName,
5577
+ settings: formatSettings,
5578
+ onProgress(partialResultString) {
5579
+ return onProgress(Object.freeze({
5580
+ [task.resultingParameterName]: partialResultString,
5581
+ }));
5582
+ },
5583
+ async mapCallback(subparameters, index, length) {
5584
+ let mappedParameters;
5585
+ try {
5586
+ mappedParameters = mapAvailableToExpectedParameters({
5587
+ expectedParameters: Object.fromEntries(task.foreach.inputSubparameterNames.map((subparameterName) => [subparameterName, null])),
5588
+ availableParameters: subparameters,
5589
+ });
5493
5590
  }
5494
- throw new PipelineExecutionError(spaceTrim__default["default"]((block) => `
5495
- ${error.message}
5591
+ catch (error) {
5592
+ if (!(error instanceof PipelineExecutionError)) {
5593
+ throw error;
5594
+ }
5595
+ const highLevelError = new PipelineExecutionError(spaceTrim__default["default"]((block) => `
5596
+ ${error.message}
5496
5597
 
5497
- This is error in FOREACH command
5498
- You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command
5598
+ This is error in FOREACH command when mapping ${formatDefinition.formatName} ${subvalueParser.subvalueName} data (${index + 1}/${length})
5599
+ You have probably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command
5499
5600
 
5500
- ${block(pipelineIdentification)}
5501
- Subparameter index: ${index}
5502
- `));
5503
- }
5504
- const allSubparameters = {
5505
- ...parameters,
5506
- ...mappedParameters,
5507
- };
5508
- // 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
5509
- Object.freeze(allSubparameters);
5510
- const subresultString = await executeAttempts({
5511
- ...options,
5512
- priority: priority + index,
5513
- parameters: allSubparameters,
5514
- pipelineIdentification: spaceTrim__default["default"]((block) => `
5515
- ${block(pipelineIdentification)}
5516
- Subparameter index: ${index}
5517
- `),
5518
- });
5519
- return subresultString;
5601
+ ${block(pipelineIdentification)}
5602
+ `));
5603
+ if (length > BIG_DATASET_TRESHOLD) {
5604
+ console.error(highLevelError);
5605
+ return FAILED_VALUE_PLACEHOLDER;
5606
+ }
5607
+ throw highLevelError;
5608
+ }
5609
+ const allSubparameters = {
5610
+ ...parameters,
5611
+ ...mappedParameters,
5612
+ };
5613
+ Object.freeze(allSubparameters);
5614
+ try {
5615
+ const subresultString = await executeAttempts({
5616
+ ...options,
5617
+ priority: priority + index,
5618
+ parameters: allSubparameters,
5619
+ pipelineIdentification: spaceTrim__default["default"]((block) => `
5620
+ ${block(pipelineIdentification)}
5621
+ Subparameter index: ${index}
5622
+ `),
5623
+ });
5624
+ return subresultString;
5625
+ }
5626
+ catch (error) {
5627
+ if (length > BIG_DATASET_TRESHOLD) {
5628
+ console.error(spaceTrim__default["default"]((block) => `
5629
+ ${error.message}
5630
+
5631
+ This is error in FOREACH command when processing ${formatDefinition.formatName} ${subvalueParser.subvalueName} data (${index + 1}/${length})
5632
+
5633
+ ${block(pipelineIdentification)}
5634
+ `));
5635
+ return FAILED_VALUE_PLACEHOLDER;
5636
+ }
5637
+ throw error;
5638
+ }
5639
+ },
5520
5640
  });
5521
5641
  return resultString;
5522
5642
  }
5523
5643
 
5524
5644
  /**
5525
- * @@@
5645
+ * Returns the context for a given task, typically used to provide additional information or variables
5646
+ * required for the execution of the task within a pipeline. The context is returned as a string value
5647
+ * that may include markdown formatting.
5526
5648
  *
5649
+ * @param task - The task for which the context is being generated. This should be a deeply immutable TaskJson object.
5650
+ * @returns The context as a string, formatted as markdown and parameter value.
5527
5651
  * @private internal utility of `createPipelineExecutor`
5528
5652
  */
5529
5653
  async function getContextForTask(task) {
@@ -5531,7 +5655,7 @@
5531
5655
  }
5532
5656
 
5533
5657
  /**
5534
- * @@@
5658
+ * Retrieves example values or templates for a given task, used to guide or validate pipeline execution.
5535
5659
  *
5536
5660
  * @private internal utility of `createPipelineExecutor`
5537
5661
  */
@@ -5540,91 +5664,128 @@
5540
5664
  }
5541
5665
 
5542
5666
  /**
5543
- * @@@
5667
+ * Computes the cosine similarity between two embedding vectors
5668
+ *
5669
+ * Note: This is helping function for RAG (retrieval-augmented generation)
5544
5670
  *
5545
- * Here is the place where RAG (retrieval-augmented generation) happens
5671
+ * @param embeddingVector1
5672
+ * @param embeddingVector2
5673
+ * @returns Cosine similarity between the two vectors
5674
+ *
5675
+ * @public exported from `@promptbook/core`
5676
+ */
5677
+ function computeCosineSimilarity(embeddingVector1, embeddingVector2) {
5678
+ if (embeddingVector1.length !== embeddingVector2.length) {
5679
+ throw new TypeError('Embedding vectors must have the same length');
5680
+ }
5681
+ const dotProduct = embeddingVector1.reduce((sum, value, index) => sum + value * embeddingVector2[index], 0);
5682
+ const magnitude1 = Math.sqrt(embeddingVector1.reduce((sum, value) => sum + value * value, 0));
5683
+ const magnitude2 = Math.sqrt(embeddingVector2.reduce((sum, value) => sum + value * value, 0));
5684
+ return 1 - dotProduct / (magnitude1 * magnitude2);
5685
+ }
5686
+
5687
+ /**
5688
+ *
5689
+ * @param knowledgePieces
5690
+ * @returns
5691
+ *
5692
+ * @private internal utility of `createPipelineExecutor`
5693
+ */
5694
+ function knowledgePiecesToString(knowledgePieces) {
5695
+ return knowledgePieces
5696
+ .map((knowledgePiece) => {
5697
+ const { content } = knowledgePiece;
5698
+ return `- ${content}`;
5699
+ })
5700
+ .join('\n');
5701
+ // <- TODO: [🧠] Some smarter aggregation of knowledge pieces, single-line vs multi-line vs mixed
5702
+ }
5703
+
5704
+ /**
5705
+ * Retrieves the most relevant knowledge pieces for a given task using embedding-based similarity search.
5706
+ * This is where retrieval-augmented generation (RAG) is performed to enhance the task with external knowledge.
5546
5707
  *
5547
5708
  * @private internal utility of `createPipelineExecutor`
5548
5709
  */
5549
5710
  async function getKnowledgeForTask(options) {
5550
- const { tools, preparedPipeline, task } = options;
5711
+ const { tools, preparedPipeline, task, parameters } = options;
5551
5712
  const firstKnowlegePiece = preparedPipeline.knowledgePieces[0];
5552
5713
  const firstKnowlegeIndex = firstKnowlegePiece === null || firstKnowlegePiece === void 0 ? void 0 : firstKnowlegePiece.index[0];
5553
5714
  // <- TODO: Do not use just first knowledge piece and first index to determine embedding model, use also keyword search
5554
5715
  if (firstKnowlegePiece === undefined || firstKnowlegeIndex === undefined) {
5555
- return 'No knowledge pieces found';
5716
+ return ''; // <- Note: Np knowledge present, return empty string
5556
5717
  }
5557
- // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
5558
- const _llms = arrayableToArray(tools.llm);
5559
- const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
5560
- const taskEmbeddingPrompt = {
5561
- title: 'Knowledge Search',
5562
- modelRequirements: {
5563
- modelVariant: 'EMBEDDING',
5564
- modelName: firstKnowlegeIndex.modelName,
5565
- },
5566
- content: task.content,
5567
- parameters: {
5568
- /* !!!!!!!! */
5569
- },
5570
- };
5571
- const taskEmbeddingResult = await llmTools.callEmbeddingModel(taskEmbeddingPrompt);
5572
- const knowledgePiecesWithRelevance = preparedPipeline.knowledgePieces.map((knowledgePiece) => {
5573
- const { index } = knowledgePiece;
5574
- const knowledgePieceIndex = index.find((i) => i.modelName === firstKnowlegeIndex.modelName);
5575
- // <- TODO: Do not use just first knowledge piece and first index to determine embedding model
5576
- if (knowledgePieceIndex === undefined) {
5718
+ try {
5719
+ // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
5720
+ const _llms = arrayableToArray(tools.llm);
5721
+ const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
5722
+ const taskEmbeddingPrompt = {
5723
+ title: 'Knowledge Search',
5724
+ modelRequirements: {
5725
+ modelVariant: 'EMBEDDING',
5726
+ modelName: firstKnowlegeIndex.modelName,
5727
+ },
5728
+ content: task.content,
5729
+ parameters,
5730
+ };
5731
+ const taskEmbeddingResult = await llmTools.callEmbeddingModel(taskEmbeddingPrompt);
5732
+ const knowledgePiecesWithRelevance = preparedPipeline.knowledgePieces.map((knowledgePiece) => {
5733
+ const { index } = knowledgePiece;
5734
+ const knowledgePieceIndex = index.find((i) => i.modelName === firstKnowlegeIndex.modelName);
5735
+ // <- TODO: Do not use just first knowledge piece and first index to determine embedding model
5736
+ if (knowledgePieceIndex === undefined) {
5737
+ return {
5738
+ content: knowledgePiece.content,
5739
+ relevance: 0,
5740
+ };
5741
+ }
5742
+ const relevance = computeCosineSimilarity(knowledgePieceIndex.position, taskEmbeddingResult.content);
5577
5743
  return {
5578
5744
  content: knowledgePiece.content,
5579
- relevance: 0,
5745
+ relevance,
5580
5746
  };
5581
- }
5582
- const relevance = computeCosineSimilarity(knowledgePieceIndex.position, taskEmbeddingResult.content);
5583
- return {
5584
- content: knowledgePiece.content,
5585
- relevance,
5586
- };
5587
- });
5588
- const knowledgePiecesSorted = knowledgePiecesWithRelevance.sort((a, b) => a.relevance - b.relevance);
5589
- const knowledgePiecesLimited = knowledgePiecesSorted.slice(0, 5);
5590
- console.log('!!! Embedding', {
5591
- task,
5592
- taskEmbeddingPrompt,
5593
- taskEmbeddingResult,
5594
- firstKnowlegePiece,
5595
- firstKnowlegeIndex,
5596
- knowledgePiecesWithRelevance,
5597
- knowledgePiecesSorted,
5598
- knowledgePiecesLimited,
5599
- });
5600
- return knowledgePiecesLimited.map(({ content }) => `- ${content}`).join('\n');
5601
- // <- TODO: [🧠] Some smart aggregation of knowledge pieces, single-line vs multi-line vs mixed
5602
- }
5603
- // TODO: !!!!!! Annotate + to new file
5604
- function computeCosineSimilarity(embeddingVector1, embeddingVector2) {
5605
- if (embeddingVector1.length !== embeddingVector2.length) {
5606
- throw new TypeError('Embedding vectors must have the same length');
5747
+ });
5748
+ const knowledgePiecesSorted = knowledgePiecesWithRelevance.sort((a, b) => a.relevance - b.relevance);
5749
+ const knowledgePiecesLimited = knowledgePiecesSorted.slice(0, 5);
5750
+ /*
5751
+ console.log('`getKnowledgeForTask` Embedding', {
5752
+ task,
5753
+ taskEmbeddingPrompt,
5754
+ taskEmbeddingResult,
5755
+ firstKnowlegePiece,
5756
+ firstKnowlegeIndex,
5757
+ knowledgePiecesWithRelevance,
5758
+ knowledgePiecesSorted,
5759
+ knowledgePiecesLimited,
5760
+ });
5761
+ */
5762
+ return knowledgePiecesToString(knowledgePiecesLimited);
5763
+ }
5764
+ catch (error) {
5765
+ assertsError(error);
5766
+ console.error('Error in `getKnowledgeForTask`', error);
5767
+ // Note: If the LLM fails, just return all knowledge pieces
5768
+ return knowledgePiecesToString(preparedPipeline.knowledgePieces);
5607
5769
  }
5608
- const dotProduct = embeddingVector1.reduce((sum, value, index) => sum + value * embeddingVector2[index], 0);
5609
- const magnitude1 = Math.sqrt(embeddingVector1.reduce((sum, value) => sum + value * value, 0));
5610
- const magnitude2 = Math.sqrt(embeddingVector2.reduce((sum, value) => sum + value * value, 0));
5611
- return 1 - dotProduct / (magnitude1 * magnitude2);
5612
5770
  }
5613
5771
  /**
5614
- * TODO: !!!! Verify if this is working
5615
5772
  * TODO: [♨] Implement Better - use keyword search
5616
5773
  * TODO: [♨] Examples of values
5617
5774
  */
5618
5775
 
5619
5776
  /**
5620
- * @@@
5777
+ * Retrieves all reserved parameters for a given pipeline task, including context, knowledge, examples, and metadata.
5778
+ * Ensures all reserved parameters are defined and throws if any are missing.
5779
+ *
5780
+ * @param options - Options including tools, pipeline, task, and context.
5781
+ * @returns An object containing all reserved parameters for the task.
5621
5782
  *
5622
5783
  * @private internal utility of `createPipelineExecutor`
5623
5784
  */
5624
5785
  async function getReservedParametersForTask(options) {
5625
- const { tools, preparedPipeline, task, pipelineIdentification } = options;
5786
+ const { tools, preparedPipeline, task, parameters, pipelineIdentification, isVerbose } = options;
5626
5787
  const context = await getContextForTask(); // <- [🏍]
5627
- const knowledge = await getKnowledgeForTask({ tools, preparedPipeline, task });
5788
+ const knowledge = await getKnowledgeForTask({ tools, preparedPipeline, task, parameters });
5628
5789
  const examples = await getExamplesForTask();
5629
5790
  const currentDate = new Date().toISOString(); // <- TODO: [🧠][💩] Better
5630
5791
  const modelName = RESERVED_PARAMETER_MISSING_VALUE;
@@ -5636,6 +5797,9 @@
5636
5797
  currentDate,
5637
5798
  modelName,
5638
5799
  };
5800
+ if (isVerbose) {
5801
+ console.info('Reserved parameters for task:', { options, reservedParameters });
5802
+ }
5639
5803
  // Note: Doublecheck that ALL reserved parameters are defined:
5640
5804
  for (const parameterName of RESERVED_PARAMETER_NAMES) {
5641
5805
  if (reservedParameters[parameterName] === undefined) {
@@ -5650,23 +5814,21 @@
5650
5814
  }
5651
5815
 
5652
5816
  /**
5653
- * @@@
5817
+ * Executes a single task within a pipeline, handling parameter validation, error checking, and progress reporting.
5818
+ *
5819
+ * @param options - Options for execution, including the task, pipeline, parameters, and callbacks.
5820
+ * @returns The output parameters produced by the task.
5654
5821
  *
5655
5822
  * @private internal utility of `createPipelineExecutor`
5656
5823
  */
5657
5824
  async function executeTask(options) {
5658
5825
  const { currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, } = options;
5659
5826
  const priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
5660
- await onProgress({
5661
- outputParameters: {
5662
- [currentTask.resultingParameterName]: '', // <- TODO: [🧠] What is the best value here?
5663
- },
5664
- });
5665
5827
  // Note: Check consistency of used and dependent parameters which was also done in `validatePipeline`, but it’s good to doublecheck
5666
5828
  const usedParameterNames = extractParameterNamesFromTask(currentTask);
5667
5829
  const dependentParameterNames = new Set(currentTask.dependentParameterNames);
5668
5830
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
5669
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
5831
+ if (difference(union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)), new Set(RESERVED_PARAMETER_NAMES)).size !== 0) {
5670
5832
  throw new UnexpectedError(spaceTrim.spaceTrim((block) => `
5671
5833
  Dependent parameters are not consistent with used parameters:
5672
5834
 
@@ -5684,13 +5846,16 @@
5684
5846
 
5685
5847
  `));
5686
5848
  }
5849
+ const reservedParameters = await getReservedParametersForTask({
5850
+ tools,
5851
+ preparedPipeline,
5852
+ task: currentTask,
5853
+ pipelineIdentification,
5854
+ parameters: parametersToPass,
5855
+ isVerbose,
5856
+ });
5687
5857
  const definedParameters = Object.freeze({
5688
- ...(await getReservedParametersForTask({
5689
- tools,
5690
- preparedPipeline,
5691
- task: currentTask,
5692
- pipelineIdentification,
5693
- })),
5858
+ ...reservedParameters,
5694
5859
  ...parametersToPass,
5695
5860
  });
5696
5861
  const definedParameterNames = new Set(Object.keys(definedParameters));
@@ -5735,6 +5900,7 @@
5735
5900
  preparedPipeline,
5736
5901
  tools,
5737
5902
  $executionReport,
5903
+ onProgress,
5738
5904
  pipelineIdentification,
5739
5905
  maxExecutionAttempts,
5740
5906
  maxParallelCount,
@@ -5762,7 +5928,8 @@
5762
5928
  */
5763
5929
 
5764
5930
  /**
5765
- * @@@
5931
+ * Filters and returns only the output parameters from the provided pipeline execution options.
5932
+ * Adds warnings for any expected output parameters that are missing.
5766
5933
  *
5767
5934
  * @private internal utility of `createPipelineExecutor`
5768
5935
  */
@@ -5787,9 +5954,12 @@
5787
5954
  }
5788
5955
 
5789
5956
  /**
5790
- * @@@
5957
+ * Executes an entire pipeline, resolving tasks in dependency order, handling errors, and reporting progress.
5958
+ *
5959
+ * Note: This is not a `PipelineExecutor` (which is bound to a single pipeline), but a utility function used by `createPipelineExecutor` to create a `PipelineExecutor`.
5791
5960
  *
5792
- * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
5961
+ * @param options - Options for execution, including input parameters, pipeline, and callbacks.
5962
+ * @returns The result of the pipeline execution, including output parameters, errors, and usage statistics.
5793
5963
  *
5794
5964
  * @private internal utility of `createPipelineExecutor`
5795
5965
  */
@@ -6112,10 +6282,27 @@
6112
6282
  cacheDirname,
6113
6283
  intermediateFilesStrategy,
6114
6284
  isAutoInstalled,
6285
+ }).catch((error) => {
6286
+ assertsError(error);
6287
+ return exportJson({
6288
+ name: 'pipelineExecutorResult',
6289
+ message: `Unuccessful PipelineExecutorResult, last catch`,
6290
+ order: [],
6291
+ value: {
6292
+ isSuccessful: false,
6293
+ errors: [serializeError(error)],
6294
+ warnings: [],
6295
+ usage: UNCERTAIN_USAGE,
6296
+ executionReport: null,
6297
+ outputParameters: {},
6298
+ preparedPipeline,
6299
+ },
6300
+ });
6115
6301
  });
6116
6302
  };
6117
6303
  const pipelineExecutor = (inputParameters) => createTask({
6118
6304
  taskType: 'EXECUTION',
6305
+ title: pipeline.title,
6119
6306
  taskProcessCallback(updateOngoingResult) {
6120
6307
  return pipelineExecutorWithCallback(inputParameters, async (newOngoingResult) => {
6121
6308
  updateOngoingResult(newOngoingResult);
@@ -6127,10 +6314,10 @@
6127
6314
  }
6128
6315
 
6129
6316
  /**
6130
- * @@@
6317
+ * Register for LLM tools.
6131
6318
  *
6132
6319
  * Note: `$` is used to indicate that this interacts with the global scope
6133
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
6320
+ * @singleton Only one instance of each register is created per build, but there can be more instances across different builds or environments.
6134
6321
  * @public exported from `@promptbook/core`
6135
6322
  */
6136
6323
  const $llmToolsRegister = new $Register('llm_execution_tools_constructors');
@@ -6139,10 +6326,10 @@
6139
6326
  */
6140
6327
 
6141
6328
  /**
6142
- * @@@
6329
+ * Register for LLM tools metadata.
6143
6330
  *
6144
6331
  * Note: `$` is used to indicate that this interacts with the global scope
6145
- * @singleton Only one instance of each register is created per build, but thare can be more @@@
6332
+ * @singleton Only one instance of each register is created per build, but there can be more instances across different builds or environments.
6146
6333
  * @public exported from `@promptbook/core`
6147
6334
  */
6148
6335
  const $llmToolsMetadataRegister = new $Register('llm_tools_metadata');
@@ -6275,11 +6462,16 @@
6275
6462
  */
6276
6463
 
6277
6464
  /**
6278
- * @@@
6465
+ * Creates LLM execution tools from provided configuration objects
6466
+ *
6467
+ * Instantiates and configures LLM tool instances for each configuration entry,
6468
+ * combining them into a unified interface via MultipleLlmExecutionTools.
6279
6469
  *
6280
6470
  * Note: This function is not cached, every call creates new instance of `MultipleLlmExecutionTools`
6281
6471
  *
6282
- * @returns @@@
6472
+ * @param configuration Array of LLM tool configurations to instantiate
6473
+ * @param options Additional options for configuring the LLM tools
6474
+ * @returns A unified interface combining all successfully instantiated LLM tools
6283
6475
  * @public exported from `@promptbook/core`
6284
6476
  */
6285
6477
  function createLlmToolsFromConfiguration(configuration, options = {}) {
@@ -6318,7 +6510,11 @@
6318
6510
  /**
6319
6511
  * TODO: [🎌] Together with `createLlmToolsFromConfiguration` + 'EXECUTION_TOOLS_CLASSES' gets to `@promptbook/core` ALL model providers, make this more efficient
6320
6512
  * TODO: [🧠][🎌] Dynamically install required providers
6321
- * TODO: @@@ write discussion about this - wizzard
6513
+ * TODO: We should implement an interactive configuration wizard that would:
6514
+ * 1. Detect which LLM providers are available in the environment
6515
+ * 2. Guide users through required configuration settings for each provider
6516
+ * 3. Allow testing connections before completing setup
6517
+ * 4. Generate appropriate configuration code for application integration
6322
6518
  * TODO: [🧠][🍛] Which name is better `createLlmToolsFromConfig` or `createLlmToolsFromConfiguration`?
6323
6519
  * TODO: [🧠] Is there some meaningfull way how to test this util
6324
6520
  * TODO: This should be maybe not under `_common` but under `utils`
@@ -6326,11 +6522,9 @@
6326
6522
  */
6327
6523
 
6328
6524
  /**
6329
- * @@@
6330
- *
6331
- * 1) @@@
6332
- * 2) @@@
6333
- *
6525
+ * Provides a collection of scrapers optimized for Node.js environment.
6526
+ * 1) `provideScrapersForNode` use as default
6527
+ * 2) `provideScrapersForBrowser` use in limited browser environment *
6334
6528
  * @public exported from `@promptbook/node`
6335
6529
  */
6336
6530
  async function $provideScrapersForNode(tools, options) {
@@ -6355,11 +6549,11 @@
6355
6549
  */
6356
6550
 
6357
6551
  /**
6358
- * @@@
6552
+ * Normalizes a given text to camelCase format.
6359
6553
  *
6360
- * @param text @@@
6361
- * @param _isFirstLetterCapital @@@
6362
- * @returns @@@
6554
+ * @param text The text to be normalized.
6555
+ * @param _isFirstLetterCapital Whether the first letter should be capitalized.
6556
+ * @returns The camelCase formatted string.
6363
6557
  * @example 'helloWorld'
6364
6558
  * @example 'iLovePromptbook'
6365
6559
  * @public exported from `@promptbook/utils`
@@ -6489,11 +6683,11 @@
6489
6683
  }
6490
6684
 
6491
6685
  /**
6492
- * @@@
6686
+ * Converts a name string into a URI-compatible format.
6493
6687
  *
6494
- * @param name @@@
6495
- * @returns @@@
6496
- * @example @@@
6688
+ * @param name The string to be converted to a URI-compatible format.
6689
+ * @returns A URI-compatible string derived from the input name.
6690
+ * @example 'Hello World' -> 'hello-world'
6497
6691
  * @public exported from `@promptbook/utils`
6498
6692
  */
6499
6693
  function nameToUriPart(name) {
@@ -6507,11 +6701,11 @@
6507
6701
  }
6508
6702
 
6509
6703
  /**
6510
- * @@@
6704
+ * Converts a given name into URI-compatible parts.
6511
6705
  *
6512
- * @param name @@@
6513
- * @returns @@@
6514
- * @example @@@
6706
+ * @param name The name to be converted into URI parts.
6707
+ * @returns An array of URI-compatible parts derived from the name.
6708
+ * @example 'Example Name' -> ['example', 'name']
6515
6709
  * @public exported from `@promptbook/utils`
6516
6710
  */
6517
6711
  function nameToUriParts(name) {
@@ -6544,9 +6738,9 @@
6544
6738
  /**
6545
6739
  * Removes quotes from a string
6546
6740
  *
6547
- * Tip: This is very usefull for post-processing of the result of the LLM model
6741
+ * Tip: This is very useful for post-processing of the result of the LLM model
6548
6742
  * Note: This function removes only the same quotes from the beginning and the end of the string
6549
- * Note: There are two simmilar functions:
6743
+ * Note: There are two similar functions:
6550
6744
  * - `removeQuotes` which removes only bounding quotes
6551
6745
  * - `unwrapResult` which removes whole introduce sentence
6552
6746
  *
@@ -6558,7 +6752,7 @@
6558
6752
  if (text.startsWith('"') && text.endsWith('"')) {
6559
6753
  return text.slice(1, -1);
6560
6754
  }
6561
- if (text.startsWith('\'') && text.endsWith('\'')) {
6755
+ if (text.startsWith("'") && text.endsWith("'")) {
6562
6756
  return text.slice(1, -1);
6563
6757
  }
6564
6758
  return text;
@@ -6567,7 +6761,7 @@
6567
6761
  /**
6568
6762
  * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
6569
6763
  *
6570
- * Note: This is usefull for post-processing of the result of the chat LLM model
6764
+ * Note: This is useful for post-processing of the result of the chat LLM model
6571
6765
  * when the model wraps the result in the (markdown) code block.
6572
6766
  *
6573
6767
  * @public exported from `@promptbook/utils`
@@ -6586,7 +6780,7 @@
6586
6780
  /**
6587
6781
  * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
6588
6782
  *
6589
- * Note: This is usefull for post-processing of the result of the completion LLM model
6783
+ * Note: This is useful for post-processing of the result of the completion LLM model
6590
6784
  * if you want to start code block in the prompt but you don't want to end it in the result.
6591
6785
  *
6592
6786
  * @public exported from `@promptbook/utils`
@@ -6601,9 +6795,9 @@
6601
6795
  /**
6602
6796
  * Removes quotes and optional introduce text from a string
6603
6797
  *
6604
- * Tip: This is very usefull for post-processing of the result of the LLM model
6798
+ * Tip: This is very useful for post-processing of the result of the LLM model
6605
6799
  * Note: This function trims the text and removes whole introduce sentence if it is present
6606
- * Note: There are two simmilar functions:
6800
+ * Note: There are two similar functions:
6607
6801
  * - `removeQuotes` which removes only bounding quotes
6608
6802
  * - `unwrapResult` which removes whole introduce sentence
6609
6803
  *
@@ -6674,8 +6868,8 @@
6674
6868
  *
6675
6869
  * - When there are multiple or no code blocks the function throws a `ParseError`
6676
6870
  *
6677
- * Note: There are multiple simmilar function:
6678
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
6871
+ * Note: There are multiple similar functions:
6872
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
6679
6873
  * - `extractJsonBlock` extracts exactly one valid JSON code block
6680
6874
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
6681
6875
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
@@ -6705,7 +6899,7 @@
6705
6899
  *
6706
6900
  * - When there are multiple or no code blocks the function throws a `ParseError`
6707
6901
  *
6708
- * Note: There are multiple simmilar function:
6902
+ * Note: There are multiple similar function:
6709
6903
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
6710
6904
  * - `extractJsonBlock` extracts exactly one valid JSON code block
6711
6905
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
@@ -6742,7 +6936,7 @@
6742
6936
  })();
6743
6937
  }
6744
6938
  /**
6745
- * TODO: Probbably remove in favour of `keepImported`
6939
+ * TODO: Probably remove in favour of `keepImported`
6746
6940
  * TODO: [1] This maybe does memory leak
6747
6941
  */
6748
6942
 
@@ -6946,7 +7140,7 @@
6946
7140
  */
6947
7141
 
6948
7142
  /**
6949
- * Placeholder for better implementation of JavascriptExecutionTools - some propper sandboxing
7143
+ * Placeholder for better implementation of JavascriptExecutionTools - some proper sandboxing
6950
7144
  *
6951
7145
  * @alias JavascriptExecutionTools
6952
7146
  * @public exported from `@promptbook/javascript`
@@ -6969,15 +7163,15 @@
6969
7163
  * Note: [🟢] Code in this file should never be never released in packages that could be imported into browser environment
6970
7164
  */
6971
7165
 
6972
- // TODO: !!!! List running services from REMOTE_SERVER_URLS
6973
- // TODO: !!!! Import directly from YML
7166
+ // TODO: [🥺] List running services from REMOTE_SERVER_URLS
7167
+ // TODO: [🥺] Import directly from YML
6974
7168
  /**
6975
- * @private !!!! Decide how to expose this
7169
+ * @private [🥺] Decide how to expose this
6976
7170
  */
6977
7171
  const openapiJson = {
6978
7172
  openapi: '3.0.0',
6979
7173
  info: {
6980
- title: 'Promptbook Remote Server API (!!!! From YML)',
7174
+ title: 'Promptbook Remote Server API ([🥺] From YML)',
6981
7175
  version: '1.0.0',
6982
7176
  description: 'API documentation for the Promptbook Remote Server',
6983
7177
  },
@@ -7600,7 +7794,7 @@
7600
7794
  // TODO: [main] !!4 Validate here userId (pass validator as dependency)
7601
7795
  let llm;
7602
7796
  if (isAnonymous === true) {
7603
- // Note: Anonymouse mode
7797
+ // Note: Anonymous mode
7604
7798
  // TODO: Maybe check that configuration is not empty
7605
7799
  const { llmToolsConfiguration } = identification;
7606
7800
  llm = createLlmToolsFromConfiguration(llmToolsConfiguration, { isVerbose });
@@ -7610,7 +7804,7 @@
7610
7804
  llm = await createLlmExecutionTools(identification);
7611
7805
  }
7612
7806
  else {
7613
- throw new PipelineExecutionError(`You must provide either llmToolsConfiguration or non-anonymous mode must be propperly configured`);
7807
+ throw new PipelineExecutionError(`You must provide either llmToolsConfiguration or non-anonymous mode must be properly configured`);
7614
7808
  }
7615
7809
  const customExecutionTools = createExecutionTools ? await createExecutionTools(identification) : {};
7616
7810
  const fs = customExecutionTools.fs || $provideFilesystemForNode();
@@ -7635,7 +7829,7 @@
7635
7829
  response.setHeader('X-Powered-By', 'Promptbook engine');
7636
7830
  next();
7637
7831
  });
7638
- // TODO: !!!! Expose openapiJson to consumer and also allow to add new routes
7832
+ // TODO: [🥺] Expose openapiJson to consumer and also allow to add new routes
7639
7833
  app.use(OpenApiValidator__namespace.middleware({
7640
7834
  apiSpec: openapiJson,
7641
7835
  ignorePaths(path) {
@@ -7675,7 +7869,7 @@
7675
7869
 
7676
7870
  **Server port:** ${port}
7677
7871
  **Startup date:** ${startupDate.toISOString()}
7678
- **Anonymouse mode:** ${isAnonymousModeAllowed ? 'enabled' : 'disabled'}
7872
+ **Anonymous mode:** ${isAnonymousModeAllowed ? 'enabled' : 'disabled'}
7679
7873
  **Application mode:** ${isApplicationModeAllowed ? 'enabled' : 'disabled'}
7680
7874
  ${block(!isApplicationModeAllowed || collection === null
7681
7875
  ? ''
@@ -7705,7 +7899,7 @@
7705
7899
  To connect to this server use:
7706
7900
 
7707
7901
  1) The client https://www.npmjs.com/package/@promptbook/remote-client
7708
- 2) OpenAI compatible client *(Not wotking yet)*
7902
+ 2) OpenAI compatible client *(Not working yet)*
7709
7903
  3) REST API
7710
7904
 
7711
7905
  For more information look at:
@@ -7789,12 +7983,13 @@
7789
7983
  });
7790
7984
  function exportExecutionTask(executionTask, isFull) {
7791
7985
  // <- TODO: [🧠] This should be maybe method of `ExecutionTask` itself
7792
- const { taskType, taskId, status, errors, warnings, createdAt, updatedAt, currentValue } = executionTask;
7986
+ const { taskType, promptbookVersion, taskId, title, status, errors, warnings, createdAt, updatedAt, currentValue, } = executionTask;
7793
7987
  if (isFull) {
7794
7988
  return {
7795
- nonce: '✨',
7796
7989
  taskId,
7990
+ title,
7797
7991
  taskType,
7992
+ promptbookVersion,
7798
7993
  status,
7799
7994
  errors: errors.map(serializeError),
7800
7995
  warnings: warnings.map(serializeError),
@@ -7805,9 +8000,10 @@
7805
8000
  }
7806
8001
  else {
7807
8002
  return {
7808
- nonce: '✨',
7809
8003
  taskId,
8004
+ title,
7810
8005
  taskType,
8006
+ promptbookVersion,
7811
8007
  status,
7812
8008
  createdAt,
7813
8009
  updatedAt,
@@ -7957,7 +8153,7 @@
7957
8153
  }
7958
8154
  });
7959
8155
  // -----------
7960
- // TODO: [👒] Listing models (and checking configuration) probbably should go through REST API not Socket.io
8156
+ // TODO: [👒] Listing models (and checking configuration) probably should go through REST API not Socket.io
7961
8157
  socket.on('listModels-request', async (request) => {
7962
8158
  const { identification } = request;
7963
8159
  if (isVerbose) {
@@ -7979,7 +8175,7 @@
7979
8175
  }
7980
8176
  });
7981
8177
  // -----------
7982
- // TODO: [👒] Listing models (and checking configuration) probbably should go through REST API not Socket.io
8178
+ // TODO: [👒] Listing models (and checking configuration) probably should go through REST API not Socket.io
7983
8179
  socket.on('preparePipeline-request', async (request) => {
7984
8180
  const { identification, pipeline } = request;
7985
8181
  if (isVerbose) {
@@ -8039,7 +8235,7 @@
8039
8235
  };
8040
8236
  }
8041
8237
  /**
8042
- * TODO: [🌡] Add CORS and security - probbably via `helmet`
8238
+ * TODO: [🌡] Add CORS and security - probably via `helmet`
8043
8239
  * TODO: Split this file into multiple functions - handler for each request
8044
8240
  * TODO: Maybe use `$exportJson`
8045
8241
  * TODO: [🧠][🛍] Maybe not `isAnonymous: boolean` BUT `mode: 'ANONYMOUS'|'COLLECTION'`