@promptbook/pdf 0.84.0-9 → 0.85.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +21 -5
  2. package/esm/index.es.js +384 -229
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/cli.index.d.ts +4 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +12 -4
  6. package/esm/typings/src/_packages/deepseek.index.d.ts +8 -0
  7. package/esm/typings/src/_packages/types.index.d.ts +16 -2
  8. package/esm/typings/src/_packages/utils.index.d.ts +2 -2
  9. package/esm/typings/src/_packages/wizzard.index.d.ts +4 -0
  10. package/esm/typings/src/cli/cli-commands/_boilerplate.d.ts +13 -0
  11. package/esm/typings/src/cli/cli-commands/about.d.ts +4 -1
  12. package/esm/typings/src/cli/cli-commands/hello.d.ts +3 -1
  13. package/esm/typings/src/cli/cli-commands/list-models.d.ts +3 -1
  14. package/esm/typings/src/cli/cli-commands/list-scrapers.d.ts +13 -0
  15. package/esm/typings/src/cli/cli-commands/make.d.ts +3 -1
  16. package/esm/typings/src/cli/cli-commands/prettify.d.ts +3 -1
  17. package/esm/typings/src/cli/cli-commands/run.d.ts +3 -1
  18. package/esm/typings/src/cli/cli-commands/runInteractiveChatbot.d.ts +1 -1
  19. package/esm/typings/src/cli/cli-commands/start-server.d.ts +13 -0
  20. package/esm/typings/src/cli/cli-commands/test-command.d.ts +3 -1
  21. package/esm/typings/src/config.d.ts +27 -1
  22. package/esm/typings/src/conversion/compilePipelineOnRemoteServer.d.ts +1 -1
  23. package/esm/typings/src/execution/AbstractTaskResult.d.ts +25 -0
  24. package/esm/typings/src/execution/ExecutionTask.d.ts +71 -0
  25. package/esm/typings/src/execution/FilesystemTools.d.ts +1 -1
  26. package/esm/typings/src/execution/PipelineExecutor.d.ts +2 -5
  27. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +2 -15
  28. package/esm/typings/src/execution/PromptbookFetch.d.ts +8 -1
  29. package/esm/typings/src/execution/{assertsExecutionSuccessful.d.ts → assertsTaskSuccessful.d.ts} +4 -3
  30. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +0 -3
  31. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +2 -6
  32. package/esm/typings/src/execution/createPipelineExecutor/20-executeTask.d.ts +3 -6
  33. package/esm/typings/src/llm-providers/_common/register/$registeredLlmToolsMessage.d.ts +9 -0
  34. package/esm/typings/src/llm-providers/deepseek/DeepseekExecutionToolsOptions.d.ts +9 -0
  35. package/esm/typings/src/llm-providers/deepseek/createDeepseekExecutionTools.d.ts +14 -0
  36. package/esm/typings/src/llm-providers/deepseek/register-configuration.d.ts +14 -0
  37. package/esm/typings/src/llm-providers/deepseek/register-constructor.d.ts +15 -0
  38. package/esm/typings/src/pipeline/book-notation.d.ts +3 -2
  39. package/esm/typings/src/pipeline/prompt-notation.d.ts +18 -5
  40. package/esm/typings/src/prepare/preparePipelineOnRemoteServer.d.ts +1 -1
  41. package/esm/typings/src/remote-server/socket-types/_subtypes/PromptbookServer_Identification.d.ts +5 -2
  42. package/esm/typings/src/remote-server/startRemoteServer.d.ts +1 -0
  43. package/esm/typings/src/types/typeAliases.d.ts +2 -0
  44. package/esm/typings/src/utils/editable/edit-pipeline-string/deflatePipeline.test.d.ts +1 -0
  45. package/esm/typings/src/utils/editable/utils/isFlatPipeline.test.d.ts +1 -0
  46. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +3 -0
  47. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +3 -0
  48. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +3 -0
  49. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +3 -0
  50. package/esm/typings/src/utils/files/mimeTypeToExtension.d.ts +10 -0
  51. package/esm/typings/src/utils/files/mimeTypeToExtension.test.d.ts +1 -0
  52. package/esm/typings/src/utils/random/$randomSeed.d.ts +2 -1
  53. package/esm/typings/src/utils/random/$randomToken.d.ts +13 -0
  54. package/esm/typings/src/wizzard/wizzard.d.ts +8 -3
  55. package/package.json +11 -16
  56. package/umd/index.umd.js +385 -232
  57. package/umd/index.umd.js.map +1 -1
  58. package/esm/typings/src/remote-server/socket-types/_common/PromptbookServer_Progress.d.ts +0 -10
  59. package/esm/typings/src/types/TaskProgress.d.ts +0 -43
package/umd/index.umd.js CHANGED
@@ -1,14 +1,15 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs/promises'), require('spacetrim'), require('crypto-js'), require('crypto-js/enc-hex'), require('path'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('mime-types'), require('papaparse')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'fs/promises', 'spacetrim', 'crypto-js', 'crypto-js/enc-hex', 'path', 'prettier', 'prettier/parser-html', 'waitasecond', 'mime-types', 'papaparse'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-pdf"] = {}, global.promises, global.spaceTrim, global.cryptoJs, global.hexEncoder, global.path, global.prettier, global.parserHtml, global.waitasecond, global.mimeTypes, global.papaparse));
5
- })(this, (function (exports, promises, spaceTrim, cryptoJs, hexEncoder, path, prettier, parserHtml, waitasecond, mimeTypes, papaparse) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs/promises'), require('spacetrim'), require('crypto-js'), require('crypto-js/enc-hex'), require('path'), require('prettier'), require('prettier/parser-html'), require('rxjs'), require('crypto'), require('waitasecond'), require('crypto-js/sha256'), require('mime-types'), require('papaparse')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'fs/promises', 'spacetrim', 'crypto-js', 'crypto-js/enc-hex', 'path', 'prettier', 'prettier/parser-html', 'rxjs', 'crypto', 'waitasecond', 'crypto-js/sha256', 'mime-types', 'papaparse'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-pdf"] = {}, global.promises, global.spaceTrim, global.cryptoJs, global.hexEncoder, global.path, global.prettier, global.parserHtml, global.rxjs, global.crypto, global.waitasecond, global.sha256, global.mimeTypes, global.papaparse));
5
+ })(this, (function (exports, promises, spaceTrim, cryptoJs, hexEncoder, path, prettier, parserHtml, rxjs, crypto, waitasecond, sha256, mimeTypes, papaparse) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
10
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
11
11
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
12
+ var sha256__default = /*#__PURE__*/_interopDefaultLegacy(sha256);
12
13
 
13
14
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
14
15
  /**
@@ -24,7 +25,7 @@
24
25
  * @generated
25
26
  * @see https://github.com/webgptorg/promptbook
26
27
  */
27
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
28
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0';
28
29
  /**
29
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
30
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -195,6 +196,12 @@
195
196
  * @public exported from `@promptbook/core`
196
197
  */
197
198
  var DEFAULT_BOOK_TITLE = "\u2728 Untitled Book";
199
+ /**
200
+ * Maximum file size limit
201
+ *
202
+ * @public exported from `@promptbook/core`
203
+ */
204
+ var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
198
205
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
199
206
  /**
200
207
  * The maximum number of iterations for a loops
@@ -228,6 +235,12 @@
228
235
  * @private within the repository - too low-level in comparison with other `MAX_...`
229
236
  */
230
237
  var IMMEDIATE_TIME = 10;
238
+ /**
239
+ * The maximum length of the (generated) filename
240
+ *
241
+ * @public exported from `@promptbook/core`
242
+ */
243
+ var MAX_FILENAME_LENGTH = 30;
231
244
  /**
232
245
  * Strategy for caching the intermediate results for knowledge sources
233
246
  *
@@ -247,6 +260,15 @@
247
260
  * @public exported from `@promptbook/core`
248
261
  */
249
262
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
263
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
264
+ /**
265
+ * Where to store the temporary downloads
266
+ *
267
+ * Note: When the folder does not exist, it is created recursively
268
+ *
269
+ * @public exported from `@promptbook/core`
270
+ */
271
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
250
272
  /**
251
273
  * Where to store the scrape cache
252
274
  *
@@ -367,6 +389,9 @@
367
389
  * @public exported from `@promptbook/utils`
368
390
  */
369
391
  var $isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
392
+ /**
393
+ * TODO: [🎺]
394
+ */
370
395
 
371
396
  /**
372
397
  * Checks if the file exists
@@ -941,24 +966,18 @@
941
966
  var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md",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.md`\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.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md",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.md`\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.md"},{title:"Prepare Knowledge-piece Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.book.md",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.md`\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.md"},{title:"Prepare Persona",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.book.md",formfactorName:"GENERIC",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Persona\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-persona.book.md`\n- INPUT PARAMETER `{availableModelNames}` List of available model names separated by comma (,)\n- INPUT PARAMETER `{personaDescription}` Description of the persona\n- OUTPUT PARAMETER `{modelRequirements}` Specific requirements for the model\n\n## Make modelRequirements\n\n- FORMAT JSON\n\n```markdown\nYou are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n\\`\\`\\`json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n\\`\\`\\`\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}\n```\n\n`-> {modelRequirements}`\n"}],sourceFile:"./books/prepare-persona.book.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-title.book.md",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.md`\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.md"}];
942
967
 
943
968
  /**
944
- * Function isValidJsonString will tell you if the string is valid JSON or not
969
+ * Checks if value is valid email
945
970
  *
946
971
  * @public exported from `@promptbook/utils`
947
972
  */
948
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
949
- try {
950
- JSON.parse(value);
951
- return true;
973
+ function isValidEmail(email) {
974
+ if (typeof email !== 'string') {
975
+ return false;
952
976
  }
953
- catch (error) {
954
- if (!(error instanceof Error)) {
955
- throw error;
956
- }
957
- if (error.message.includes('Unexpected token')) {
958
- return false;
959
- }
977
+ if (email.split('\n').length > 1) {
960
978
  return false;
961
979
  }
980
+ return /^.+@.+\..+$/.test(email);
962
981
  }
963
982
 
964
983
  /**
@@ -980,6 +999,27 @@
980
999
  * TODO: Maybe split `ParseError` and `ApplyError`
981
1000
  */
982
1001
 
1002
+ /**
1003
+ * Function isValidJsonString will tell you if the string is valid JSON or not
1004
+ *
1005
+ * @public exported from `@promptbook/utils`
1006
+ */
1007
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
1008
+ try {
1009
+ JSON.parse(value);
1010
+ return true;
1011
+ }
1012
+ catch (error) {
1013
+ if (!(error instanceof Error)) {
1014
+ throw error;
1015
+ }
1016
+ if (error.message.includes('Unexpected token')) {
1017
+ return false;
1018
+ }
1019
+ return false;
1020
+ }
1021
+ }
1022
+
983
1023
  /**
984
1024
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
985
1025
  * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
@@ -993,6 +1033,15 @@
993
1033
  if (isValidJsonString(pipelineString)) {
994
1034
  throw new ParseError('Expected a book, but got a JSON string');
995
1035
  }
1036
+ else if (isValidUrl(pipelineString)) {
1037
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
1038
+ }
1039
+ else if (isValidFilePath(pipelineString)) {
1040
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
1041
+ }
1042
+ else if (isValidEmail(pipelineString)) {
1043
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
1044
+ }
996
1045
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
997
1046
  return pipelineString;
998
1047
  }
@@ -2193,6 +2242,58 @@
2193
2242
  return PipelineExecutionError;
2194
2243
  }(Error));
2195
2244
 
2245
+ /**
2246
+ * Determine if the pipeline is fully prepared
2247
+ *
2248
+ * @see https://github.com/webgptorg/promptbook/discussions/196
2249
+ *
2250
+ * @public exported from `@promptbook/core`
2251
+ */
2252
+ function isPipelinePrepared(pipeline) {
2253
+ // Note: Ignoring `pipeline.preparations` @@@
2254
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2255
+ if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
2256
+ return false;
2257
+ }
2258
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2259
+ return false;
2260
+ }
2261
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2262
+ return false;
2263
+ }
2264
+ /*
2265
+ TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
2266
+ > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
2267
+ > return false;
2268
+ > }
2269
+ */
2270
+ return true;
2271
+ }
2272
+ /**
2273
+ * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
2274
+ * TODO: [🐠] Maybe base this on `makeValidator`
2275
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2276
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2277
+ * - [🏍] ? Is context in each task
2278
+ * - [♨] Are examples prepared
2279
+ * - [♨] Are tasks prepared
2280
+ */
2281
+
2282
+ /**
2283
+ * Generates random token
2284
+ *
2285
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
2286
+ *
2287
+ * @private internal helper function
2288
+ * @returns secure random token
2289
+ */
2290
+ function $randomToken(randomness) {
2291
+ return crypto.randomBytes(randomness).toString('hex');
2292
+ }
2293
+ /**
2294
+ * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
2295
+ */
2296
+
2196
2297
  /**
2197
2298
  * This error indicates problems parsing the format value
2198
2299
  *
@@ -2374,12 +2475,28 @@
2374
2475
  /**
2375
2476
  * Asserts that the execution of a Promptbook is successful
2376
2477
  *
2478
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2479
+ *
2377
2480
  * @param executionResult - The partial result of the Promptbook execution
2378
2481
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2379
- * @public exported from `@promptbook/core`
2482
+ * @private internal helper function of `asPromise` method of `ExecutionTask`
2380
2483
  */
2381
- function assertsExecutionSuccessful(executionResult) {
2382
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2484
+ function assertsTaskSuccessful(executionResult) {
2485
+ var e_1, _a;
2486
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
2487
+ try {
2488
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
2489
+ var warning = warnings_1_1.value;
2490
+ console.warn(warning.message);
2491
+ }
2492
+ }
2493
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2494
+ finally {
2495
+ try {
2496
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
2497
+ }
2498
+ finally { if (e_1) throw e_1.error; }
2499
+ }
2383
2500
  if (isSuccessful === true) {
2384
2501
  return;
2385
2502
  }
@@ -2399,122 +2516,55 @@
2399
2516
  }
2400
2517
  }
2401
2518
  /**
2402
- * TODO: [🐚] This function should be removed OR changed OR be completely rewritten
2403
2519
  * TODO: [🧠] Can this return type be better typed than void
2404
2520
  */
2405
2521
 
2406
2522
  /**
2407
- * Determine if the pipeline is fully prepared
2408
- *
2409
- * @see https://github.com/webgptorg/promptbook/discussions/196
2523
+ * Helper to create a new task
2410
2524
  *
2411
- * @public exported from `@promptbook/core`
2525
+ * @private internal helper function
2412
2526
  */
2413
- function isPipelinePrepared(pipeline) {
2414
- // Note: Ignoring `pipeline.preparations` @@@
2415
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2416
- if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
2417
- return false;
2418
- }
2419
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2420
- return false;
2421
- }
2422
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2423
- return false;
2527
+ function createTask(options) {
2528
+ var taskType = options.taskType, taskProcessCallback = options.taskProcessCallback;
2529
+ var taskId = "".concat(taskType.toLowerCase(), "-").concat($randomToken(256 /* <- TODO: !!! To global config */));
2530
+ var resultSubject = new rxjs.BehaviorSubject({});
2531
+ var finalResultPromise = /* not await */ taskProcessCallback(function (newOngoingResult) {
2532
+ resultSubject.next(newOngoingResult);
2533
+ });
2534
+ function asPromise(options) {
2535
+ return __awaiter(this, void 0, void 0, function () {
2536
+ var _a, isCrashedOnError, finalResult;
2537
+ return __generator(this, function (_b) {
2538
+ switch (_b.label) {
2539
+ case 0:
2540
+ _a = (options || {}).isCrashedOnError, isCrashedOnError = _a === void 0 ? true : _a;
2541
+ return [4 /*yield*/, finalResultPromise];
2542
+ case 1:
2543
+ finalResult = _b.sent();
2544
+ if (isCrashedOnError) {
2545
+ assertsTaskSuccessful(finalResult);
2546
+ }
2547
+ return [2 /*return*/, finalResult];
2548
+ }
2549
+ });
2550
+ });
2424
2551
  }
2425
- /*
2426
- TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
2427
- > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
2428
- > return false;
2429
- > }
2430
- */
2431
- return true;
2552
+ return {
2553
+ taskType: taskType,
2554
+ taskId: taskId,
2555
+ asPromise: asPromise,
2556
+ asObservable: function () {
2557
+ return rxjs.concat(resultSubject.asObservable(), rxjs.from(asPromise({
2558
+ isCrashedOnError: true,
2559
+ })));
2560
+ },
2561
+ };
2432
2562
  }
2433
2563
  /**
2434
- * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
2435
- * TODO: [🐠] Maybe base this on `makeValidator`
2436
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2437
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2438
- * - [🏍] ? Is context in each task
2439
- * - [♨] Are examples prepared
2440
- * - [♨] Are tasks prepared
2564
+ * TODO: Maybe allow to terminate the task and add getter `isFinished` or `status`
2565
+ * TODO: [🐚] Split into more files and make `PrepareTask` & `RemoteTask` + split the function
2441
2566
  */
2442
2567
 
2443
- /**
2444
- * Format either small or big number
2445
- *
2446
- * @public exported from `@promptbook/utils`
2447
- */
2448
- function numberToString(value) {
2449
- if (value === 0) {
2450
- return '0';
2451
- }
2452
- else if (Number.isNaN(value)) {
2453
- return VALUE_STRINGS.nan;
2454
- }
2455
- else if (value === Infinity) {
2456
- return VALUE_STRINGS.infinity;
2457
- }
2458
- else if (value === -Infinity) {
2459
- return VALUE_STRINGS.negativeInfinity;
2460
- }
2461
- for (var exponent = 0; exponent < 15; exponent++) {
2462
- var factor = Math.pow(10, exponent);
2463
- var valueRounded = Math.round(value * factor) / factor;
2464
- if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
2465
- return valueRounded.toFixed(exponent);
2466
- }
2467
- }
2468
- return value.toString();
2469
- }
2470
-
2471
- /**
2472
- * Function `valueToString` will convert the given value to string
2473
- * This is useful and used in the `templateParameters` function
2474
- *
2475
- * Note: This function is not just calling `toString` method
2476
- * It's more complex and can handle this conversion specifically for LLM models
2477
- * See `VALUE_STRINGS`
2478
- *
2479
- * Note: There are 2 similar functions
2480
- * - `valueToString` converts value to string for LLM models as human-readable string
2481
- * - `asSerializable` converts value to string to preserve full information to be able to convert it back
2482
- *
2483
- * @public exported from `@promptbook/utils`
2484
- */
2485
- function valueToString(value) {
2486
- try {
2487
- if (value === '') {
2488
- return VALUE_STRINGS.empty;
2489
- }
2490
- else if (value === null) {
2491
- return VALUE_STRINGS.null;
2492
- }
2493
- else if (value === undefined) {
2494
- return VALUE_STRINGS.undefined;
2495
- }
2496
- else if (typeof value === 'string') {
2497
- return value;
2498
- }
2499
- else if (typeof value === 'number') {
2500
- return numberToString(value);
2501
- }
2502
- else if (value instanceof Date) {
2503
- return value.toISOString();
2504
- }
2505
- else {
2506
- return JSON.stringify(value);
2507
- }
2508
- }
2509
- catch (error) {
2510
- if (!(error instanceof Error)) {
2511
- throw error;
2512
- }
2513
- console.error(error);
2514
- return VALUE_STRINGS.unserializable;
2515
- }
2516
- }
2517
-
2518
2568
  /**
2519
2569
  * Serializes an error into a [🚉] JSON-serializable object
2520
2570
  *
@@ -3016,7 +3066,7 @@
3016
3066
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
3017
3067
  throw error_1;
3018
3068
  }
3019
- errors.push(error_1);
3069
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
3020
3070
  return [3 /*break*/, 13];
3021
3071
  case 13:
3022
3072
  _b = _a.next();
@@ -3043,7 +3093,10 @@
3043
3093
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
3044
3094
  // 3) ...
3045
3095
  spaceTrim__default["default"](function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
3046
- .map(function (error, i) { return "".concat(i + 1, ") **").concat(error.name || 'Error', ":** ").concat(error.message); })
3096
+ .map(function (_a, i) {
3097
+ var error = _a.error, llmExecutionTools = _a.llmExecutionTools;
3098
+ return "".concat(i + 1, ") **").concat(llmExecutionTools.title, "** thrown **").concat(error.name || 'Error', ":** ").concat(error.message);
3099
+ })
3047
3100
  .join('\n')), "\n\n "); }));
3048
3101
  }
3049
3102
  else if (this.llmExecutionTools.length === 0) {
@@ -3174,10 +3227,9 @@
3174
3227
  return modelName;
3175
3228
  })
3176
3229
  .join(',');
3177
- return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
3230
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription }).asPromise()];
3178
3231
  case 3:
3179
3232
  result = _d.sent();
3180
- assertsExecutionSuccessful(result);
3181
3233
  outputParameters = result.outputParameters;
3182
3234
  modelRequirementsRaw = outputParameters.modelRequirements;
3183
3235
  modelRequirements = JSON.parse(modelRequirementsRaw);
@@ -3525,6 +3577,17 @@
3525
3577
  return match ? match[1].toLowerCase() : null;
3526
3578
  }
3527
3579
 
3580
+ /**
3581
+ * Convert mime type to file extension
3582
+ *
3583
+ * Note: If the mime type is invalid, `null` is returned
3584
+ *
3585
+ * @private within the repository
3586
+ */
3587
+ function mimeTypeToExtension(value) {
3588
+ return mimeTypes.extension(value) || null;
3589
+ }
3590
+
3528
3591
  /**
3529
3592
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
3530
3593
  *
@@ -3560,9 +3623,9 @@
3560
3623
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3561
3624
  var _a;
3562
3625
  return __awaiter(this, void 0, void 0, function () {
3563
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
3564
- return __generator(this, function (_f) {
3565
- switch (_f.label) {
3626
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, basename, hash, rootDirname_1, filepath, fileContent, _f, _g, filename_1, fileExtension, mimeType;
3627
+ return __generator(this, function (_h) {
3628
+ switch (_h.label) {
3566
3629
  case 0:
3567
3630
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
3568
3631
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -3571,54 +3634,76 @@
3571
3634
  if (!name) {
3572
3635
  name = knowledgeSourceContentToName(knowledgeSourceContent);
3573
3636
  }
3574
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
3637
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
3575
3638
  url = knowledgeSourceContent;
3576
3639
  return [4 /*yield*/, fetch(url)];
3577
3640
  case 1:
3578
- response_1 = _f.sent();
3641
+ response_1 = _h.sent();
3579
3642
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
3580
- return [2 /*return*/, {
3581
- source: name,
3582
- filename: null,
3583
- url: url,
3584
- mimeType: mimeType,
3585
- /*
3586
- TODO: [🥽]
3587
- > async asBlob() {
3588
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3589
- > const content = await response.blob();
3590
- > return content;
3591
- > },
3592
- */
3593
- asJson: function () {
3594
- return __awaiter(this, void 0, void 0, function () {
3595
- var content;
3596
- return __generator(this, function (_a) {
3597
- switch (_a.label) {
3598
- case 0: return [4 /*yield*/, response_1.json()];
3599
- case 1:
3600
- content = _a.sent();
3601
- return [2 /*return*/, content];
3602
- }
3643
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
3644
+ return [2 /*return*/, {
3645
+ source: name,
3646
+ filename: null,
3647
+ url: url,
3648
+ mimeType: mimeType,
3649
+ /*
3650
+ TODO: [🥽]
3651
+ > async asBlob() {
3652
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3653
+ > const content = await response.blob();
3654
+ > return content;
3655
+ > },
3656
+ */
3657
+ asJson: function () {
3658
+ return __awaiter(this, void 0, void 0, function () {
3659
+ var content;
3660
+ return __generator(this, function (_a) {
3661
+ switch (_a.label) {
3662
+ case 0: return [4 /*yield*/, response_1.json()];
3663
+ case 1:
3664
+ content = _a.sent();
3665
+ return [2 /*return*/, content];
3666
+ }
3667
+ });
3603
3668
  });
3604
- });
3605
- },
3606
- asText: function () {
3607
- return __awaiter(this, void 0, void 0, function () {
3608
- var content;
3609
- return __generator(this, function (_a) {
3610
- switch (_a.label) {
3611
- case 0: return [4 /*yield*/, response_1.text()];
3612
- case 1:
3613
- content = _a.sent();
3614
- return [2 /*return*/, content];
3615
- }
3669
+ },
3670
+ asText: function () {
3671
+ return __awaiter(this, void 0, void 0, function () {
3672
+ var content;
3673
+ return __generator(this, function (_a) {
3674
+ switch (_a.label) {
3675
+ case 0: return [4 /*yield*/, response_1.text()];
3676
+ case 1:
3677
+ content = _a.sent();
3678
+ return [2 /*return*/, content];
3679
+ }
3680
+ });
3616
3681
  });
3617
- });
3618
- },
3619
- }];
3682
+ },
3683
+ }];
3684
+ }
3685
+ basename = url.split('/').pop() || titleToName(url);
3686
+ hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
3687
+ rootDirname_1 = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
3688
+ filepath = path.join.apply(void 0, __spreadArray(__spreadArray([], __read(nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */)), false), ["".concat(basename.substring(0, MAX_FILENAME_LENGTH), ".").concat(mimeTypeToExtension(mimeType))], false));
3689
+ return [4 /*yield*/, tools.fs.mkdir(path.dirname(path.join(rootDirname_1, filepath)), { recursive: true })];
3620
3690
  case 2:
3621
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
3691
+ _h.sent();
3692
+ _g = (_f = Buffer).from;
3693
+ return [4 /*yield*/, response_1.arrayBuffer()];
3694
+ case 3:
3695
+ fileContent = _g.apply(_f, [_h.sent()]);
3696
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
3697
+ throw new LimitReachedError("File is too large (".concat(Math.round(fileContent.length / 1024 / 1024), "MB). Maximum allowed size is ").concat(Math.round(DEFAULT_MAX_FILE_SIZE / 1024 / 1024), "MB."));
3698
+ }
3699
+ return [4 /*yield*/, tools.fs.writeFile(path.join(rootDirname_1, filepath), fileContent)];
3700
+ case 4:
3701
+ _h.sent();
3702
+ // TODO: [💵] Check the file security
3703
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
3704
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
3705
+ case 5:
3706
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
3622
3707
  if (tools.fs === undefined) {
3623
3708
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
3624
3709
  // <- TODO: [🧠] What is the best error type here`
@@ -3631,8 +3716,8 @@
3631
3716
  fileExtension = getFileExtension(filename_1);
3632
3717
  mimeType = extensionToMimeType(fileExtension || '');
3633
3718
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
3634
- case 3:
3635
- if (!(_f.sent())) {
3719
+ case 6:
3720
+ if (!(_h.sent())) {
3636
3721
  throw new NotFoundError(spaceTrim__default["default"](function (block) { return "\n Can not make source handler for file which does not exist:\n\n File:\n ".concat(block(knowledgeSourceContent), "\n\n Full file path:\n ").concat(block(filename_1), "\n "); }));
3637
3722
  }
3638
3723
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -3678,7 +3763,7 @@
3678
3763
  });
3679
3764
  },
3680
3765
  }];
3681
- case 4: return [2 /*return*/, {
3766
+ case 7: return [2 /*return*/, {
3682
3767
  source: name,
3683
3768
  filename: null,
3684
3769
  url: null,
@@ -3942,10 +4027,9 @@
3942
4027
  var content = _a.content;
3943
4028
  return content;
3944
4029
  }).join('\n\n'),
3945
- })];
4030
+ }).asPromise()];
3946
4031
  case 2:
3947
4032
  result = _e.sent();
3948
- assertsExecutionSuccessful(result);
3949
4033
  outputParameters = result.outputParameters;
3950
4034
  titleRaw = outputParameters.title;
3951
4035
  if (isVerbose) {
@@ -4017,6 +4101,81 @@
4017
4101
  * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
4018
4102
  */
4019
4103
 
4104
+ /**
4105
+ * Format either small or big number
4106
+ *
4107
+ * @public exported from `@promptbook/utils`
4108
+ */
4109
+ function numberToString(value) {
4110
+ if (value === 0) {
4111
+ return '0';
4112
+ }
4113
+ else if (Number.isNaN(value)) {
4114
+ return VALUE_STRINGS.nan;
4115
+ }
4116
+ else if (value === Infinity) {
4117
+ return VALUE_STRINGS.infinity;
4118
+ }
4119
+ else if (value === -Infinity) {
4120
+ return VALUE_STRINGS.negativeInfinity;
4121
+ }
4122
+ for (var exponent = 0; exponent < 15; exponent++) {
4123
+ var factor = Math.pow(10, exponent);
4124
+ var valueRounded = Math.round(value * factor) / factor;
4125
+ if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
4126
+ return valueRounded.toFixed(exponent);
4127
+ }
4128
+ }
4129
+ return value.toString();
4130
+ }
4131
+
4132
+ /**
4133
+ * Function `valueToString` will convert the given value to string
4134
+ * This is useful and used in the `templateParameters` function
4135
+ *
4136
+ * Note: This function is not just calling `toString` method
4137
+ * It's more complex and can handle this conversion specifically for LLM models
4138
+ * See `VALUE_STRINGS`
4139
+ *
4140
+ * Note: There are 2 similar functions
4141
+ * - `valueToString` converts value to string for LLM models as human-readable string
4142
+ * - `asSerializable` converts value to string to preserve full information to be able to convert it back
4143
+ *
4144
+ * @public exported from `@promptbook/utils`
4145
+ */
4146
+ function valueToString(value) {
4147
+ try {
4148
+ if (value === '') {
4149
+ return VALUE_STRINGS.empty;
4150
+ }
4151
+ else if (value === null) {
4152
+ return VALUE_STRINGS.null;
4153
+ }
4154
+ else if (value === undefined) {
4155
+ return VALUE_STRINGS.undefined;
4156
+ }
4157
+ else if (typeof value === 'string') {
4158
+ return value;
4159
+ }
4160
+ else if (typeof value === 'number') {
4161
+ return numberToString(value);
4162
+ }
4163
+ else if (value instanceof Date) {
4164
+ return value.toISOString();
4165
+ }
4166
+ else {
4167
+ return JSON.stringify(value);
4168
+ }
4169
+ }
4170
+ catch (error) {
4171
+ if (!(error instanceof Error)) {
4172
+ throw error;
4173
+ }
4174
+ console.error(error);
4175
+ return VALUE_STRINGS.unserializable;
4176
+ }
4177
+ }
4178
+
4020
4179
  /**
4021
4180
  * Parses the given script and returns the list of all used variables that are not defined in the script
4022
4181
  *
@@ -5461,27 +5620,20 @@
5461
5620
  */
5462
5621
  function executeTask(options) {
5463
5622
  return __awaiter(this, void 0, void 0, function () {
5464
- var currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
5465
- var e_1, _f, _g;
5466
- return __generator(this, function (_h) {
5467
- switch (_h.label) {
5623
+ var currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
5624
+ var _f, e_1, _g, _h, _j;
5625
+ return __generator(this, function (_k) {
5626
+ switch (_k.label) {
5468
5627
  case 0:
5469
5628
  currentTask = options.currentTask, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, onProgress = options.onProgress, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification, maxExecutionAttempts = options.maxExecutionAttempts, maxParallelCount = options.maxParallelCount, csvSettings = options.csvSettings, isVerbose = options.isVerbose, rootDirname = options.rootDirname, cacheDirname = options.cacheDirname, intermediateFilesStrategy = options.intermediateFilesStrategy, isAutoInstalled = options.isAutoInstalled, isNotPreparedWarningSupressed = options.isNotPreparedWarningSupressed;
5470
- name = "pipeline-executor-frame-".concat(currentTask.name);
5471
- title = currentTask.title;
5472
5629
  priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
5473
5630
  return [4 /*yield*/, onProgress({
5474
- name: name,
5475
- title: title,
5476
- isStarted: false,
5477
- isDone: false,
5478
- taskType: currentTask.taskType,
5479
- parameterName: currentTask.resultingParameterName,
5480
- parameterValue: null,
5481
- // <- [🍸]
5631
+ outputParameters: (_f = {},
5632
+ _f[currentTask.resultingParameterName] = '',
5633
+ _f),
5482
5634
  })];
5483
5635
  case 1:
5484
- _h.sent();
5636
+ _k.sent();
5485
5637
  usedParameterNames = extractParameterNamesFromTask(currentTask);
5486
5638
  dependentParameterNames = new Set(currentTask.dependentParameterNames);
5487
5639
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
@@ -5500,7 +5652,7 @@
5500
5652
  pipelineIdentification: pipelineIdentification,
5501
5653
  })];
5502
5654
  case 2:
5503
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
5655
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_k.sent())])), parametersToPass])]);
5504
5656
  definedParameterNames = new Set(Object.keys(definedParameters));
5505
5657
  parameters = {};
5506
5658
  _loop_1 = function (parameterName) {
@@ -5528,7 +5680,7 @@
5528
5680
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
5529
5681
  finally {
5530
5682
  try {
5531
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
5683
+ if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
5532
5684
  }
5533
5685
  finally { if (e_1) throw e_1.error; }
5534
5686
  }
@@ -5559,24 +5711,19 @@
5559
5711
  isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
5560
5712
  })];
5561
5713
  case 3:
5562
- resultString = _h.sent();
5714
+ resultString = _k.sent();
5563
5715
  return [4 /*yield*/, onProgress({
5564
- name: name,
5565
- title: title,
5566
- isStarted: true,
5567
- isDone: true,
5568
- taskType: currentTask.taskType,
5569
- parameterName: currentTask.resultingParameterName,
5570
- parameterValue: resultString,
5571
- // <- [🍸]
5716
+ outputParameters: (_h = {},
5717
+ _h[currentTask.resultingParameterName] = resultString,
5718
+ _h),
5572
5719
  })];
5573
5720
  case 4:
5574
- _h.sent();
5575
- return [2 /*return*/, Object.freeze((_g = {},
5576
- _g[currentTask.resultingParameterName] =
5721
+ _k.sent();
5722
+ return [2 /*return*/, Object.freeze((_j = {},
5723
+ _j[currentTask.resultingParameterName] =
5577
5724
  // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
5578
5725
  resultString,
5579
- _g))];
5726
+ _j))];
5580
5727
  }
5581
5728
  });
5582
5729
  });
@@ -5584,9 +5731,6 @@
5584
5731
  /**
5585
5732
  * TODO: [🤹‍♂️]
5586
5733
  */
5587
- /**
5588
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5589
- */
5590
5734
 
5591
5735
  /**
5592
5736
  * @@@
@@ -5848,15 +5992,15 @@
5848
5992
  return [3 /*break*/, 4];
5849
5993
  case 3:
5850
5994
  unresovedTasks_1 = unresovedTasks_1.filter(function (task) { return task !== currentTask; });
5851
- work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (progress) {
5995
+ work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (newOngoingResult) {
5852
5996
  if (isReturned) {
5853
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
5997
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(newOngoingResult, null, 4)
5854
5998
  .split('\n')
5855
5999
  .map(function (line) { return "> ".concat(line); })
5856
6000
  .join('\n')), "\n "); }));
5857
6001
  }
5858
6002
  if (onProgress) {
5859
- onProgress(progress);
6003
+ onProgress(newOngoingResult);
5860
6004
  }
5861
6005
  }, $executionReport: executionReport, pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Task name: ").concat(currentTask.name, "\n Task title: ").concat(currentTask.title, "\n "); }) }))
5862
6006
  .then(function (newParametersToPass) {
@@ -5959,9 +6103,6 @@
5959
6103
  });
5960
6104
  });
5961
6105
  }
5962
- /**
5963
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5964
- */
5965
6106
 
5966
6107
  /**
5967
6108
  * Creates executor function from pipeline and execution tools.
@@ -5993,7 +6134,7 @@
5993
6134
  console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
5994
6135
  }
5995
6136
  var runCount = 0;
5996
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
6137
+ var pipelineExecutorWithCallback = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
5997
6138
  return __generator(this, function (_a) {
5998
6139
  runCount++;
5999
6140
  return [2 /*return*/, /* not await */ executePipeline({
@@ -6018,11 +6159,23 @@
6018
6159
  })];
6019
6160
  });
6020
6161
  }); };
6162
+ var pipelineExecutor = function (inputParameters) {
6163
+ return createTask({
6164
+ taskType: 'EXECUTION',
6165
+ taskProcessCallback: function (updateOngoingResult) {
6166
+ var _this = this;
6167
+ return pipelineExecutorWithCallback(inputParameters, function (newOngoingResult) { return __awaiter(_this, void 0, void 0, function () {
6168
+ return __generator(this, function (_a) {
6169
+ updateOngoingResult(newOngoingResult);
6170
+ return [2 /*return*/];
6171
+ });
6172
+ }); });
6173
+ },
6174
+ });
6175
+ };
6176
+ // <- TODO: Make types such as there is no need to do `as` for `createTask`
6021
6177
  return pipelineExecutor;
6022
6178
  }
6023
- /**
6024
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
6025
- */
6026
6179
 
6027
6180
  /**
6028
6181
  * Metadata of the scraper
@@ -6124,10 +6277,9 @@
6124
6277
  return [4 /*yield*/, source.asText()];
6125
6278
  case 4:
6126
6279
  knowledgeContent = _k.sent();
6127
- return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent })];
6280
+ return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent }).asPromise()];
6128
6281
  case 5:
6129
6282
  result = _k.sent();
6130
- assertsExecutionSuccessful(result);
6131
6283
  outputParameters = result.outputParameters;
6132
6284
  knowledgePiecesRaw = outputParameters.knowledgePieces;
6133
6285
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
@@ -6150,13 +6302,13 @@
6150
6302
  _c.label = 1;
6151
6303
  case 1:
6152
6304
  _c.trys.push([1, 7, , 8]);
6153
- return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent })];
6305
+ return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6154
6306
  case 2:
6155
6307
  titleResult = _c.sent();
6156
6308
  _a = titleResult.outputParameters.title, titleRaw = _a === void 0 ? 'Untitled' : _a;
6157
6309
  title = spaceTrim__default["default"](titleRaw) /* <- TODO: Maybe do in pipeline */;
6158
6310
  name = titleToName(title);
6159
- return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent })];
6311
+ return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6160
6312
  case 3:
6161
6313
  keywordsResult = _c.sent();
6162
6314
  _b = keywordsResult.outputParameters.keywords, keywordsRaw = _b === void 0 ? '' : _b;
@@ -6234,7 +6386,7 @@
6234
6386
  className: 'MarkitdownScraper',
6235
6387
  mimeTypes: [
6236
6388
  'application/pdf',
6237
- // TODO: Make priority for scrapers and than allow all mime types here:
6389
+ // TODO: [💵] Make priority for scrapers and than analyze which mime-types can Markitdown scrape and allow all mime types here:
6238
6390
  // 'text/html',
6239
6391
  // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
6240
6392
  ],
@@ -6270,10 +6422,10 @@
6270
6422
  this.tools = tools;
6271
6423
  this.options = options;
6272
6424
  this.markdownScraper = new MarkdownScraper(tools, options);
6425
+ // Note: Module `markitdown-ts` has no types available, so it is imported using `require`
6273
6426
  // eslint-disable-next-line @typescript-eslint/no-var-requires
6274
6427
  var MarkItDown = require('markitdown-ts').MarkItDown;
6275
- // <- TODO: !!! Use Markitdown directly not through this package
6276
- // <- Note: !!!!!!!
6428
+ // <- TODO: [🍀] Use Markitdown directly not through this package
6277
6429
  this.markitdown = new MarkItDown();
6278
6430
  }
6279
6431
  Object.defineProperty(MarkitdownScraper.prototype, "metadata", {
@@ -6318,12 +6470,12 @@
6318
6470
  case 2:
6319
6471
  if (!!(_f.sent())) return [3 /*break*/, 5];
6320
6472
  src = source.filename || source.url || null;
6321
- console.log('!!!', { src: src, source: source, cacheFilehandler: cacheFilehandler });
6473
+ // console.log('!!', { src, source, cacheFilehandler });
6322
6474
  if (src === null) {
6323
6475
  throw new UnexpectedError('Source has no filename or url');
6324
6476
  }
6325
6477
  return [4 /*yield*/, this.markitdown.convert(src, {
6326
- // TODO: !!!!!! Pass when sacraping Youtube
6478
+ // TODO: Pass when sacraping Youtube
6327
6479
  // enableYoutubeTranscript: true,
6328
6480
  // youtubeTranscriptLanguage: 'en',
6329
6481
  })];
@@ -6331,11 +6483,12 @@
6331
6483
  result = _f.sent();
6332
6484
  if (result === null || result === undefined) {
6333
6485
  throw new Error("Markitdown could not convert the \"".concat(source.source, "\""));
6334
- // <- TODO: !!! Make MarkitdownError
6486
+ // <- TODO: [🍀] Make MarkitdownError
6335
6487
  }
6336
- console.log('!!!', { result: result, cacheFilehandler: cacheFilehandler });
6488
+ // console.log('!!', { result, cacheFilehandler });
6337
6489
  return [4 /*yield*/, this.tools.fs.writeFile(cacheFilehandler.filename, result.text_content)];
6338
6490
  case 4:
6491
+ // console.log('!!', { result, cacheFilehandler });
6339
6492
  _f.sent();
6340
6493
  _f.label = 5;
6341
6494
  case 5: return [2 /*return*/, cacheFilehandler];