@promptbook/markdown-utils 0.89.0 → 0.92.0-10

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 (27) hide show
  1. package/README.md +4 -0
  2. package/esm/index.es.js +173 -30
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +6 -0
  5. package/esm/typings/src/_packages/deepseek.index.d.ts +2 -0
  6. package/esm/typings/src/_packages/google.index.d.ts +2 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  8. package/esm/typings/src/cli/common/$provideLlmToolsForCli.d.ts +1 -1
  9. package/esm/typings/src/conversion/archive/loadArchive.d.ts +2 -2
  10. package/esm/typings/src/execution/CommonToolsOptions.d.ts +4 -0
  11. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTask.d.ts +12 -0
  12. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTask.d.ts +5 -0
  13. package/esm/typings/src/formats/csv/utils/csvParse.d.ts +12 -0
  14. package/esm/typings/src/formats/json/utils/jsonParse.d.ts +11 -0
  15. package/esm/typings/src/llm-providers/_common/filterModels.d.ts +15 -0
  16. package/esm/typings/src/llm-providers/_common/register/LlmToolsMetadata.d.ts +43 -0
  17. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -0
  18. package/esm/typings/src/llm-providers/deepseek/deepseek-models.d.ts +23 -0
  19. package/esm/typings/src/llm-providers/google/google-models.d.ts +23 -0
  20. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +4 -0
  21. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  22. package/esm/typings/src/pipeline/PipelineJson/PersonaJson.d.ts +4 -2
  23. package/esm/typings/src/remote-server/openapi-types.d.ts +348 -6
  24. package/esm/typings/src/remote-server/openapi.d.ts +397 -3
  25. package/package.json +1 -1
  26. package/umd/index.umd.js +173 -30
  27. package/umd/index.umd.js.map +1 -1
package/README.md CHANGED
@@ -23,6 +23,10 @@
23
23
 
24
24
 
25
25
 
26
+ <blockquote style="color: #ff8811">
27
+ <b>⚠ Warning:</b> This is a pre-release version of the library. It is not yet ready for production use. Please look at <a href="https://www.npmjs.com/package/@promptbook/core?activeTab=versions">latest stable release</a>.
28
+ </blockquote>
29
+
26
30
  ## 📦 Package `@promptbook/markdown-utils`
27
31
 
28
32
  - Promptbooks are [divided into several](#-packages) packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook).
package/esm/index.es.js CHANGED
@@ -25,7 +25,7 @@ const BOOK_LANGUAGE_VERSION = '1.0.0';
25
25
  * @generated
26
26
  * @see https://github.com/webgptorg/promptbook
27
27
  */
28
- const PROMPTBOOK_ENGINE_VERSION = '0.89.0';
28
+ const PROMPTBOOK_ENGINE_VERSION = '0.92.0-10';
29
29
  /**
30
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
31
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -537,7 +537,7 @@ function extractJsonBlock(markdown) {
537
537
  function keepUnused(...valuesToKeep) {
538
538
  }
539
539
 
540
- 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:"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`\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"},{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"}];
540
+ 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"}];
541
541
 
542
542
  /**
543
543
  * Checks if value is valid email
@@ -1563,7 +1563,7 @@ function extractParameterNames(template) {
1563
1563
  */
1564
1564
  function unpreparePipeline(pipeline) {
1565
1565
  let { personas, knowledgeSources, tasks } = pipeline;
1566
- personas = personas.map((persona) => ({ ...persona, modelRequirements: undefined, preparationIds: undefined }));
1566
+ personas = personas.map((persona) => ({ ...persona, modelsRequirements: undefined, preparationIds: undefined }));
1567
1567
  knowledgeSources = knowledgeSources.map((knowledgeSource) => ({ ...knowledgeSource, preparationIds: undefined }));
1568
1568
  tasks = tasks.map((task) => {
1569
1569
  let { dependentParameterNames } = task;
@@ -1773,7 +1773,7 @@ function isPipelinePrepared(pipeline) {
1773
1773
  if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1774
1774
  return false;
1775
1775
  }
1776
- if (!pipeline.personas.every((persona) => persona.modelRequirements !== undefined)) {
1776
+ if (!pipeline.personas.every((persona) => persona.modelsRequirements !== undefined)) {
1777
1777
  return false;
1778
1778
  }
1779
1779
  if (!pipeline.knowledgeSources.every((knowledgeSource) => knowledgeSource.preparationIds !== undefined)) {
@@ -1797,6 +1797,45 @@ function isPipelinePrepared(pipeline) {
1797
1797
  * - [♨] Are tasks prepared
1798
1798
  */
1799
1799
 
1800
+ /**
1801
+ * Converts a JavaScript Object Notation (JSON) string into an object.
1802
+ *
1803
+ * Note: This is wrapper around `JSON.parse()` with better error and type handling
1804
+ *
1805
+ * @public exported from `@promptbook/utils`
1806
+ */
1807
+ function jsonParse(value) {
1808
+ if (value === undefined) {
1809
+ throw new Error(`Can not parse JSON from undefined value.`);
1810
+ }
1811
+ else if (typeof value !== 'string') {
1812
+ console.error('Can not parse JSON from non-string value.', { text: value });
1813
+ throw new Error(spaceTrim(`
1814
+ Can not parse JSON from non-string value.
1815
+
1816
+ The value type: ${typeof value}
1817
+ See more in console.
1818
+ `));
1819
+ }
1820
+ try {
1821
+ return JSON.parse(value);
1822
+ }
1823
+ catch (error) {
1824
+ if (!(error instanceof Error)) {
1825
+ throw error;
1826
+ }
1827
+ throw new Error(spaceTrim((block) => `
1828
+ ${block(error.message)}
1829
+
1830
+ The JSON text:
1831
+ ${block(value)}
1832
+ `));
1833
+ }
1834
+ }
1835
+ /**
1836
+ * TODO: !!!! Use in Promptbook.studio
1837
+ */
1838
+
1800
1839
  /**
1801
1840
  * Recursively converts JSON strings to JSON objects
1802
1841
 
@@ -1815,7 +1854,7 @@ function jsonStringsToJsons(object) {
1815
1854
  const newObject = { ...object };
1816
1855
  for (const [key, value] of Object.entries(object)) {
1817
1856
  if (typeof value === 'string' && isValidJsonString(value)) {
1818
- newObject[key] = JSON.parse(value);
1857
+ newObject[key] = jsonParse(value);
1819
1858
  }
1820
1859
  else {
1821
1860
  newObject[key] = jsonStringsToJsons(value);
@@ -2673,27 +2712,48 @@ async function preparePersona(personaDescription, tools, options) {
2673
2712
  pipeline: await collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-persona.book'),
2674
2713
  tools,
2675
2714
  });
2676
- // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
2677
2715
  const _llms = arrayableToArray(tools.llm);
2678
2716
  const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
2679
- const availableModels = await llmTools.listModels();
2680
- const availableModelNames = availableModels
2717
+ const availableModels = (await llmTools.listModels())
2681
2718
  .filter(({ modelVariant }) => modelVariant === 'CHAT')
2682
- .map(({ modelName }) => modelName)
2683
- .join(',');
2684
- const result = await preparePersonaExecutor({ availableModelNames, personaDescription }).asPromise();
2719
+ .map(({ modelName, modelDescription }) => ({
2720
+ modelName,
2721
+ modelDescription,
2722
+ // <- Note: `modelTitle` and `modelVariant` is not relevant for this task
2723
+ }));
2724
+ const result = await preparePersonaExecutor({
2725
+ availableModels /* <- Note: Passing as JSON */,
2726
+ personaDescription,
2727
+ }).asPromise();
2685
2728
  const { outputParameters } = result;
2686
- const { modelRequirements: modelRequirementsRaw } = outputParameters;
2687
- const modelRequirements = JSON.parse(modelRequirementsRaw);
2729
+ const { modelsRequirements: modelsRequirementsJson } = outputParameters;
2730
+ let modelsRequirementsUnchecked = jsonParse(modelsRequirementsJson);
2688
2731
  if (isVerbose) {
2689
- console.info(`PERSONA ${personaDescription}`, modelRequirements);
2732
+ console.info(`PERSONA ${personaDescription}`, modelsRequirementsUnchecked);
2690
2733
  }
2691
- const { modelName, systemMessage, temperature } = modelRequirements;
2692
- return {
2734
+ if (!Array.isArray(modelsRequirementsUnchecked)) {
2735
+ // <- TODO: Book should have syntax and system to enforce shape of JSON
2736
+ modelsRequirementsUnchecked = [modelsRequirementsUnchecked];
2737
+ /*
2738
+ throw new UnexpectedError(
2739
+ spaceTrim(
2740
+ (block) => `
2741
+ Invalid \`modelsRequirements\`:
2742
+
2743
+ \`\`\`json
2744
+ ${block(JSON.stringify(modelsRequirementsUnchecked, null, 4))}
2745
+ \`\`\`
2746
+ `,
2747
+ ),
2748
+ );
2749
+ */
2750
+ }
2751
+ const modelsRequirements = modelsRequirementsUnchecked.map((modelRequirements) => ({
2693
2752
  modelVariant: 'CHAT',
2694
- modelName,
2695
- systemMessage,
2696
- temperature,
2753
+ ...modelRequirements,
2754
+ }));
2755
+ return {
2756
+ modelsRequirements,
2697
2757
  };
2698
2758
  }
2699
2759
  /**
@@ -3517,7 +3577,7 @@ async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3517
3577
  > },
3518
3578
  */
3519
3579
  async asJson() {
3520
- return JSON.parse(await tools.fs.readFile(filename, 'utf-8'));
3580
+ return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
3521
3581
  },
3522
3582
  async asText() {
3523
3583
  return await tools.fs.readFile(filename, 'utf-8');
@@ -3775,14 +3835,14 @@ async function preparePipeline(pipeline, tools, options) {
3775
3835
  // TODO: [🖌][🧠] Implement some `mapAsync` function
3776
3836
  const preparedPersonas = new Array(personas.length);
3777
3837
  await forEachAsync(personas, { maxParallelCount /* <- TODO: [🪂] When there are subtasks, this maximul limit can be broken */ }, async (persona, index) => {
3778
- const modelRequirements = await preparePersona(persona.description, { ...tools, llm: llmToolsWithUsage }, {
3838
+ const { modelsRequirements } = await preparePersona(persona.description, { ...tools, llm: llmToolsWithUsage }, {
3779
3839
  rootDirname,
3780
3840
  maxParallelCount /* <- TODO: [🪂] */,
3781
3841
  isVerbose,
3782
3842
  });
3783
3843
  const preparedPersona = {
3784
3844
  ...persona,
3785
- modelRequirements,
3845
+ modelsRequirements,
3786
3846
  preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id],
3787
3847
  // <- TODO: [🍙] Make some standard order of json properties
3788
3848
  };
@@ -4121,6 +4181,24 @@ function isValidCsvString(value) {
4121
4181
  }
4122
4182
  }
4123
4183
 
4184
+ /**
4185
+ * Converts a CSV string into an object
4186
+ *
4187
+ * Note: This is wrapper around `papaparse.parse()` with better autohealing
4188
+ *
4189
+ * @private - for now until `@promptbook/csv` is released
4190
+ */
4191
+ function csvParse(value /* <- TODO: string_csv */, settings, schema /* <- TODO: Make CSV Schemas */) {
4192
+ settings = { ...settings, ...MANDATORY_CSV_SETTINGS };
4193
+ // Note: Autoheal invalid '\n' characters
4194
+ if (settings.newline && !settings.newline.includes('\r') && value.includes('\r')) {
4195
+ console.warn('CSV string contains carriage return characters, but in the CSV settings the `newline` setting does not include them. Autohealing the CSV string.');
4196
+ value = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
4197
+ }
4198
+ const csv = parse(value, settings);
4199
+ return csv;
4200
+ }
4201
+
4124
4202
  /**
4125
4203
  * Definition for CSV spreadsheet
4126
4204
  *
@@ -4143,8 +4221,7 @@ const CsvFormatDefinition = {
4143
4221
  {
4144
4222
  subvalueName: 'ROW',
4145
4223
  async mapValues(value, outputParameterName, settings, mapCallback) {
4146
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
4147
- const csv = parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
4224
+ const csv = csvParse(value, settings);
4148
4225
  if (csv.errors.length !== 0) {
4149
4226
  throw new CsvFormatError(spaceTrim((block) => `
4150
4227
  CSV parsing error
@@ -4174,8 +4251,7 @@ const CsvFormatDefinition = {
4174
4251
  {
4175
4252
  subvalueName: 'CELL',
4176
4253
  async mapValues(value, outputParameterName, settings, mapCallback) {
4177
- // TODO: [👨🏾‍🤝‍👨🏼] DRY csv parsing
4178
- const csv = parse(value, { ...settings, ...MANDATORY_CSV_SETTINGS });
4254
+ const csv = csvParse(value, settings);
4179
4255
  if (csv.errors.length !== 0) {
4180
4256
  throw new CsvFormatError(spaceTrim((block) => `
4181
4257
  CSV parsing error
@@ -5102,13 +5178,79 @@ async function getExamplesForTask(task) {
5102
5178
  /**
5103
5179
  * @@@
5104
5180
  *
5181
+ * Here is the place where RAG (retrieval-augmented generation) happens
5182
+ *
5105
5183
  * @private internal utility of `createPipelineExecutor`
5106
5184
  */
5107
5185
  async function getKnowledgeForTask(options) {
5108
- const { preparedPipeline, task } = options;
5109
- return preparedPipeline.knowledgePieces.map(({ content }) => `- ${content}`).join('\n');
5186
+ const { tools, preparedPipeline, task } = options;
5187
+ const firstKnowlegePiece = preparedPipeline.knowledgePieces[0];
5188
+ const firstKnowlegeIndex = firstKnowlegePiece === null || firstKnowlegePiece === void 0 ? void 0 : firstKnowlegePiece.index[0];
5189
+ // <- TODO: Do not use just first knowledge piece and first index to determine embedding model, use also keyword search
5190
+ if (firstKnowlegePiece === undefined || firstKnowlegeIndex === undefined) {
5191
+ return 'No knowledge pieces found';
5192
+ }
5193
+ // TODO: [🚐] Make arrayable LLMs -> single LLM DRY
5194
+ const _llms = arrayableToArray(tools.llm);
5195
+ const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
5196
+ const taskEmbeddingPrompt = {
5197
+ title: 'Knowledge Search',
5198
+ modelRequirements: {
5199
+ modelVariant: 'EMBEDDING',
5200
+ modelName: firstKnowlegeIndex.modelName,
5201
+ },
5202
+ content: task.content,
5203
+ parameters: {
5204
+ /* !!!!!!!! */
5205
+ },
5206
+ };
5207
+ const taskEmbeddingResult = await llmTools.callEmbeddingModel(taskEmbeddingPrompt);
5208
+ const knowledgePiecesWithRelevance = preparedPipeline.knowledgePieces.map((knowledgePiece) => {
5209
+ const { index } = knowledgePiece;
5210
+ const knowledgePieceIndex = index.find((i) => i.modelName === firstKnowlegeIndex.modelName);
5211
+ // <- TODO: Do not use just first knowledge piece and first index to determine embedding model
5212
+ if (knowledgePieceIndex === undefined) {
5213
+ return {
5214
+ content: knowledgePiece.content,
5215
+ relevance: 0,
5216
+ };
5217
+ }
5218
+ const relevance = computeCosineSimilarity(knowledgePieceIndex.position, taskEmbeddingResult.content);
5219
+ return {
5220
+ content: knowledgePiece.content,
5221
+ relevance,
5222
+ };
5223
+ });
5224
+ const knowledgePiecesSorted = knowledgePiecesWithRelevance.sort((a, b) => a.relevance - b.relevance);
5225
+ const knowledgePiecesLimited = knowledgePiecesSorted.slice(0, 5);
5226
+ console.log('!!! Embedding', {
5227
+ task,
5228
+ taskEmbeddingPrompt,
5229
+ taskEmbeddingResult,
5230
+ firstKnowlegePiece,
5231
+ firstKnowlegeIndex,
5232
+ knowledgePiecesWithRelevance,
5233
+ knowledgePiecesSorted,
5234
+ knowledgePiecesLimited,
5235
+ });
5236
+ return knowledgePiecesLimited.map(({ content }) => `- ${content}`).join('\n');
5110
5237
  // <- TODO: [🧠] Some smart aggregation of knowledge pieces, single-line vs multi-line vs mixed
5111
5238
  }
5239
+ // TODO: !!!!!! Annotate + to new file
5240
+ function computeCosineSimilarity(embeddingVector1, embeddingVector2) {
5241
+ if (embeddingVector1.length !== embeddingVector2.length) {
5242
+ throw new TypeError('Embedding vectors must have the same length');
5243
+ }
5244
+ const dotProduct = embeddingVector1.reduce((sum, value, index) => sum + value * embeddingVector2[index], 0);
5245
+ const magnitude1 = Math.sqrt(embeddingVector1.reduce((sum, value) => sum + value * value, 0));
5246
+ const magnitude2 = Math.sqrt(embeddingVector2.reduce((sum, value) => sum + value * value, 0));
5247
+ return 1 - dotProduct / (magnitude1 * magnitude2);
5248
+ }
5249
+ /**
5250
+ * TODO: !!!! Verify if this is working
5251
+ * TODO: [♨] Implement Better - use keyword search
5252
+ * TODO: [♨] Examples of values
5253
+ */
5112
5254
 
5113
5255
  /**
5114
5256
  * @@@
@@ -5116,9 +5258,9 @@ async function getKnowledgeForTask(options) {
5116
5258
  * @private internal utility of `createPipelineExecutor`
5117
5259
  */
5118
5260
  async function getReservedParametersForTask(options) {
5119
- const { preparedPipeline, task, pipelineIdentification } = options;
5261
+ const { tools, preparedPipeline, task, pipelineIdentification } = options;
5120
5262
  const context = await getContextForTask(); // <- [🏍]
5121
- const knowledge = await getKnowledgeForTask({ preparedPipeline, task });
5263
+ const knowledge = await getKnowledgeForTask({ tools, preparedPipeline, task });
5122
5264
  const examples = await getExamplesForTask();
5123
5265
  const currentDate = new Date().toISOString(); // <- TODO: [🧠][💩] Better
5124
5266
  const modelName = RESERVED_PARAMETER_MISSING_VALUE;
@@ -5180,6 +5322,7 @@ async function executeTask(options) {
5180
5322
  }
5181
5323
  const definedParameters = Object.freeze({
5182
5324
  ...(await getReservedParametersForTask({
5325
+ tools,
5183
5326
  preparedPipeline,
5184
5327
  task: currentTask,
5185
5328
  pipelineIdentification,