{"name":"@promptbook/utils","version":"0.41.2","keywords":["autogpt","openai","gpt-3","gpt-4","chatgpt","ai","machine-learning","natural-language-processing","nlp","prompt","template","pipeline","automation","text-generation","language-model"],"license":"SEE LICENSE IN LICENSE","_id":"@promptbook/utils@0.41.2","contributors":[{"url":"https://www.pavolhejny.com/","name":"Pavol Hejný","email":"me@pavolhejny.com"}],"homepage":"https://www.npmjs.com/package/@promptbook/core","bugs":{"url":"https://github.com/webgptorg/promptbook/issues"},"bin":{"promptbook":"bin/promptbook-cli.js"},"dist":{"shasum":"5c6abcc3398b8c2aab41efe0ec99f618e2d2da80","tarball":"http://registry-npm.ywwl.com/@promptbook/utils/download/@promptbook/utils-0.41.2.tgz","fileCount":355,"integrity":"sha512-uKKzyfsRrpljQaVmGXoPLb/BuVF8FznNyWo3jS6CI3R6vi66PozACMd3vCE09dqk8jmFLY5qRWNzAsUHuanXNA==","signatures":[{"sig":"MEYCIQCrok8eb7KA3ipM1BrFeVOjTok4n9c0/ept68k258UBLAIhAIgUICqWgk2sNVK3CZIpD7uDITPNdnBwhL/0o8PQo0kE","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":457188,"size":92108,"noattachment":false,"key":"/@promptbook/utils/-/@promptbook/utils-0.41.2.tgz"},"main":"./umd/index.umd.js","module":"./esm/index.es.js","gitHead":"7eda481effc1c064409fbce7aded4026052d762d","private":false,"typings":"./esm/typings/_packages/utils.index.d.ts","_npmUser":{"name":"hejny","email":"pavol@hejny.org"},"repository":{"url":"git+https://github.com/webgptorg/promptbook.git","type":"git"},"_npmVersion":"8.13.1","description":"Library to supercharge your use of large language models","directories":{},"sideEffects":false,"_nodeVersion":"18.4.0","dependencies":{"n12":"1.8.18","moment":"^2.30.1","prettier":"2.8.1","spacetrim":"0.11.2"},"_hasShrinkwrap":false,"peerDependencies":{"@promptbook/core":"0.41.0"},"_npmOperationalInternal":{"tmp":"tmp/utils_0.41.2_1711394971258_0.2352369163224668","host":"s3://npm-registry-packages"},"readme":"# ![Promptbook logo - cube with letters P and B](./other/design/logo-h1.png) Promptbook\n\nSupercharge your use of large language models\n\n\n\n\n[![NPM Version of ![Promptbook logo - cube with letters P and B](./other/design/logo-h1.png) Promptbook](https://badge.fury.io/js/promptbook.svg)](https://www.npmjs.com/package/promptbook)\n[![Quality of package ![Promptbook logo - cube with letters P and B](./other/design/logo-h1.png) Promptbook](https://packagequality.com/shield/promptbook.svg)](https://packagequality.com/#?package=promptbook)\n[![Known Vulnerabilities](https://snyk.io/test/github/webgptorg/promptbook/badge.svg)](https://snyk.io/test/github/webgptorg/promptbook)\n[![Issues](https://img.shields.io/github/issues/webgptorg/promptbook.svg?style=flat)](https://github.com/webgptorg/promptbook/issues)\n\n\n\n\n\n## 📦 Package `@promptbook/utils`\n\n- Promptbooks are [divided into several](#-packages) packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook).\n- This package `@promptbook/utils` is one part of the promptbook ecosystem.\n\nTo install this package, run:\n\n```bash\n# Install entire promptbook ecosystem\nnpm i ptbk\n\n# Install just this package to save space\nnpm i @promptbook/utils\n```\n\nUtility functions used in the library but also useful for individual use in preprocessing and postprocessing LLM inputs and outputs\n\nHere is a overview of the functions which are exported from the `@promptbook/utils` package and can be used in your own projects:\n\n## Postprocessing\n\nSometimes you need to postprocess the output of the LLM model, every postprocessing function that is available through `POSTPROCESS` command in promptbook is exported from `@promptbook/utils`. You can use:\n\n-   `spaceTrim`\n-   `extractAllBlocksFromMarkdown`, _<- Note: Exported from [`@promptbook/markdown-utils`](https://www.npmjs.com/package/@promptbook/markdown-utils)_\n-   `extractAllListItemsFromMarkdown` _<- Note: Exported from [`@promptbook/markdown-utils`](https://www.npmjs.com/package/@promptbook/markdown-utils)_\n-   `extractBlock`\n-   `extractOneBlockFromMarkdown `_<- Note: Exported from [`@promptbook/markdown-utils`](https://www.npmjs.com/package/@promptbook/markdown-utils)_\n-   `prettifyPipelineString`\n-   `removeContentComments`\n-   `removeEmojis`\n-   `removeMarkdownFormatting` _<- Note: Exported from [`@promptbook/markdown-utils`](https://www.npmjs.com/package/@promptbook/markdown-utils)_\n-   `removeQuotes`\n-   `trimCodeBlock`\n-   `trimEndOfCodeBlock`\n-   `unwrapResult`\n\nVery often you will use `unwrapResult`, which is used to extract the result you need from output with some additional information:\n\n```typescript\nimport { unwrapResult } from '@promptbook/utils';\n\nunwrapResult('Best greeting for the user is \"Hi Pavol!\"'); // 'Hi Pavol!'\n```\n\n## Templating\n\nThere is a function `replaceParameters` which is used to replace the parameters in given template optimized to LLM prompt templates.\n\n```typescript\nimport { replaceParameters } from '@promptbook/utils';\n\nreplaceParameters('Hello, {name}!', { name: 'world' }); // 'Hello, world!'\n```\n\nAnd also multiline templates with blockquotes\n\n```typescript\nimport { replaceParameters, spaceTrim } from '@promptbook/utils';\n\nreplaceParameters(\n    spaceTrim(`\n        Hello, {name}!\n\n        > {answer}\n    `),\n    {\n        name: 'world',\n        answer: spaceTrim(`\n            I'm fine,\n            thank you!\n\n            And you?\n        `),\n    },\n);\n\n// Hello, world!\n//\n// > I'm fine,\n// > thank you!\n// >\n// > And you?\n```\n\n## Counting\n\nTheese functions are usefull to count stats about the input/output in human-like terms not tokens and bytes, you can use\n`countCharacters`, `countLines`, `countPages`, `countParagraphs`, `countSentences`, `countWords`\n\n```typescript\nimport { countWords } from '@promptbook/utils';\n\nconsole.log(countWords('Hello, world!')); // 2\n```\n\n## Splitting\n\nSplitting functions are similar to counting but they return the splitted parts of the input/output, you can use\n`splitIntoCharacters`, `splitIntoLines`, `splitIntoPages`, `splitIntoParagraphs`, `splitIntoSentences`, `splitIntoWords`\n\n```typescript\nimport { splitIntoWords } from '@promptbook/utils';\n\nconsole.log(splitIntoWords('Hello, world!')); // ['Hello', 'world']\n```\n\n## Normalization\n\nNormalization functions are used to put the string into a normalized form, you can use\n`kebab-case`\n`PascalCase`\n`SCREAMING_CASE`\n`snake_case`\n`kebab-case`\n\n```typescript\nimport { normalizeTo } from '@promptbook/utils';\n\nconsole.log(normalizeTo['kebab-case']('Hello, world!')); // 'hello-world'\n```\n\n-   There are more normalization functions like `capitalize`, `decapitalize`, `removeDiacritics`,...\n-   Theese can be also used as postprocessing functions in the `POSTPROCESS` command in promptbook\n\n## Misc\n\nSee also the documentation for all the functions in the `@promptbook/utils` package, every function is documented by jsdoc, typed by typescript and tested by jest.\n\n\n\n`assertsExecutionSuccessful`,\n`checkExpectations`,\n`executionReportJsonToString`,\n`isPassingExpectations`,\n`isValidJsonString`,\n`parseNumber` \n\n\n---\n\nRest of the documentation is common for **entire promptbook ecosystem**:\n\n## 🤍 The Promptbook Whitepaper\n\nWhen you have a simple, single prompt for ChatGPT, GPT-4, Anthropic Claude, Google Gemini, Llama 2, or whatever, it doesn't matter how it is integrated. Whether it's the direct calling of a REST API, using the SDK, hardcoding the prompt in the source code, or importing a text file, the process remains the same.\n\nIf you need something more advanced or want to extend the capabilities of LLMs, you generally have three ways to proceed:\n\n1. **Fine-tune** the model to your specifications or even train your own.\n2. **Prompt-engineer** the prompt to the best shape you can achieve.\n3. Use **multiple prompts** in a pipeline to get the best result.\n\nIn any of these situations, but especially in (3), the Promptbook library can make your life easier and make **orchestraror for your prompts**.\n\n-   **Separation of concerns** between prompt engineer and programmer; between code files and prompt files; and between prompts and their execution logic.\n-   Set up a **common format** for prompts that is interchangeable between projects and language/technology stacks.\n-   **Preprocessing** and cleaning the input data from the user.\n-   Use default values - **Jokers** to bypass some parts of the pipeline.\n-   **Expect** some specific output from the model.\n-   **Retry** mismatched outputs.\n-   **Combine** multiple models together.\n-   Interactive **User interaction** with the model and the user.\n-   Leverage **external** sources (like ChatGPT plugins or OpenAI's GPTs).\n-   Simplify your code to be **DRY** and not repeat all the boilerplate code for each prompt.\n-   **Versioning** of promptbooks\n-   **Reuse** parts of promptbooks in/between projects.\n-   Run the LLM **optimally** in parallel, with the best _cost/quality_ ratio or _speed/quality_ ratio.\n-   **Execution report** to see what happened during the execution.\n-   **Logging** the results of the promptbooks.\n-   _(Not ready yet)_ **Caching** calls to LLMs to save money and time.\n-   _(Not ready yet)_ Extend one prompt book from another one.\n-   _(Not ready yet)_ Leverage the **streaming** to make super cool UI/UX.\n-   _(Not ready yet)_ **A/B testing** to determine which prompt works best for the job.\n\n\n\n### Sample:\n\nFile `write-website-content.ptbk.md`:\n\n\n\n> # 🌍 Create website content\n>\n> Instructions for creating web page content.\n>\n> -   PIPELINE URL https://promptbook.studio/webgpt/write-website-content.ptbk.md\n> -   PROMPTBOOK VERSION 0.0.1\n> -   INPUT  PARAM `{rawTitle}` Automatically suggested a site name or empty text\n> -   INPUT  PARAM `{rawAssigment}` Automatically generated site entry from image recognition\n> -   OUTPUT PARAM `{content}` Web content\n> -   OUTPUT PARAM `{keywords}` Keywords\n>\n> ## 👤 Specifying the assigment\n>\n> What is your web about?\n>\n> -   PROMPT DIALOG\n>\n> ```\n> {rawAssigment}\n> ```\n>\n> `-> {assigment}` Website assignment and specification\n>\n> ## ✨ Improving the title\n>\n> -   MODEL VARIANT Chat\n> -   MODEL NAME `gpt-4`\n> -   POSTPROCESSING `unwrapResult`\n>\n> ```\n> As an experienced marketing specialist, you have been entrusted with improving the name of your client's business.\n>\n> A suggested name from a client:\n> \"{rawTitle}\"\n>\n> Assignment from customer:\n>\n> > {assigment}\n>\n> ## Instructions:\n>\n> -   Write only one name suggestion\n> -   The name will be used on the website, business cards, visuals, etc.\n> ```\n>\n> `-> {enhancedTitle}` Enhanced title\n>\n> ## 👤 Website title approval\n>\n> Is the title for your website okay?\n>\n> -   PROMPT DIALOG\n>\n> ```\n> {enhancedTitle}\n> ```\n>\n> `-> {title}` Title for the website\n>\n> ## 🐰 Cunning subtitle\n>\n> -   MODEL VARIANT Chat\n> -   MODEL NAME `gpt-4`\n> -   POSTPROCESSING `unwrapResult`\n>\n> ```\n> As an experienced copywriter, you have been entrusted with creating a claim for the \"{title}\" web page.\n>\n> A website assignment from a customer:\n>\n> > {assigment}\n>\n> ## Instructions:\n>\n> -   Write only one name suggestion\n> -   Claim will be used on website, business cards, visuals, etc.\n> -   Claim should be punchy, funny, original\n> ```\n>\n> `-> {claim}` Claim for the web\n>\n> ## 🚦 Keyword analysis\n>\n> -   MODEL VARIANT Chat\n> -   MODEL NAME `gpt-4`\n>\n> ```\n> As an experienced SEO specialist, you have been entrusted with creating keywords for the website \"{title}\".\n>\n> Website assignment from the customer:\n>\n> > {assigment}\n>\n> ## Instructions:\n>\n> -   Write a list of keywords\n> -   Keywords are in basic form\n>\n> ## Example:\n>\n> -   Ice cream\n> -   Olomouc\n> -   Quality\n> -   Family\n> -   Tradition\n> -   Italy\n> -   Craft\n>\n> ```\n>\n> `-> {keywords}` Keywords\n>\n> ## 🔗 Combine the beginning\n>\n> -   SIMPLE TEMPLATE\n>\n> ```\n>\n> # {title}\n>\n> > {claim}\n>\n> ```\n>\n> `-> {contentBeginning}` Beginning of web content\n>\n> ## 🖋 Write the content\n>\n> -   MODEL VARIANT Completion\n> -   MODEL NAME `gpt-3.5-turbo-instruct`\n>\n> ```\n> As an experienced copywriter and web designer, you have been entrusted with creating text for a new website {title}.\n>\n> A website assignment from a customer:\n>\n> > {assigment}\n>\n> ## Instructions:\n>\n> -   Text formatting is in Markdown\n> -   Be concise and to the point\n> -   Use keywords, but they should be naturally in the text\n> -   This is the complete content of the page, so don't forget all the important information and elements the page should contain\n> -   Use headings, bullets, text formatting\n>\n> ## Keywords:\n>\n> {keywords}\n>\n> ## Web Content:\n>\n> {contentBeginning}\n> ```\n>\n> `-> {contentBody}` Middle of the web content\n>\n> ## 🔗 Combine the content\n>\n> -   SIMPLE TEMPLATE\n>\n> ```markdown\n> {contentBeginning}\n>\n> {contentBody}\n> ```\n>\n> `-> {content}`\n\n\n\nFollowing is the scheme how the promptbook above is executed:\n\n```mermaid\n%% 🔮 Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\nflowchart LR\n  subgraph \"🌍 Create website content\"\n\n      direction TB\n\n      input((Input)):::input\n      templateSpecifyingTheAssigment(👤 Specifying the assigment)\n      input--\"{rawAssigment}\"-->templateSpecifyingTheAssigment\n      templateImprovingTheTitle(✨ Improving the title)\n      input--\"{rawTitle}\"-->templateImprovingTheTitle\n      templateSpecifyingTheAssigment--\"{assigment}\"-->templateImprovingTheTitle\n      templateWebsiteTitleApproval(👤 Website title approval)\n      templateImprovingTheTitle--\"{enhancedTitle}\"-->templateWebsiteTitleApproval\n      templateCunningSubtitle(🐰 Cunning subtitle)\n      templateWebsiteTitleApproval--\"{title}\"-->templateCunningSubtitle\n      templateSpecifyingTheAssigment--\"{assigment}\"-->templateCunningSubtitle\n      templateKeywordAnalysis(🚦 Keyword analysis)\n      templateWebsiteTitleApproval--\"{title}\"-->templateKeywordAnalysis\n      templateSpecifyingTheAssigment--\"{assigment}\"-->templateKeywordAnalysis\n      templateCombineTheBeginning(🔗 Combine the beginning)\n      templateWebsiteTitleApproval--\"{title}\"-->templateCombineTheBeginning\n      templateCunningSubtitle--\"{claim}\"-->templateCombineTheBeginning\n      templateWriteTheContent(🖋 Write the content)\n      templateWebsiteTitleApproval--\"{title}\"-->templateWriteTheContent\n      templateSpecifyingTheAssigment--\"{assigment}\"-->templateWriteTheContent\n      templateKeywordAnalysis--\"{keywords}\"-->templateWriteTheContent\n      templateCombineTheBeginning--\"{contentBeginning}\"-->templateWriteTheContent\n      templateCombineTheContent(🔗 Combine the content)\n      templateCombineTheBeginning--\"{contentBeginning}\"-->templateCombineTheContent\n      templateWriteTheContent--\"{contentBody}\"-->templateCombineTheContent\n\n      templateCombineTheContent--\"{content}\"-->output\n      output((Output)):::output\n\n      classDef input color: grey;\n      classDef output color: grey;\n\n  end;\n```\n\n[More template samples](./samples/templates/)\n\n_Note: We are using [postprocessing functions](#postprocessing-functions) like `unwrapResult` that can be used to postprocess the result._\n\n## 📦 Packages\n\nThis library is divided into several packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook).\nYou can install all of them at once:\n\n```bash\nnpm i ptbk\n```\n\nOr you can install them separately:\n\n> ⭐ Marked packages are worth to try first\n\n\n\n-   ⭐ **[ptbk](https://www.npmjs.com/package/ptbk)** - Bundle of all packages, when you want to install everything and you don't care about the size\n-   **[promptbook](https://www.npmjs.com/package/promptbook)** - Same as `ptbk`\n-   **[@promptbook/core](https://www.npmjs.com/package/@promptbook/core)** - Core of the library, it contains the main logic for promptbooks\n-   **[@promptbook/node](https://www.npmjs.com/package/@promptbook/node)** - Core of the library for Node.js\n-   ⭐ **[@promptbook/utils](https://www.npmjs.com/package/@promptbook/utils)** - Utility functions used in the library but also useful for individual use in preprocessing and postprocessing LLM inputs and outputs\n-   **[@promptbook/markdown-utils](https://www.npmjs.com/package/@promptbook/markdown-utils)** - Utility functions used for processing markdown\n-   _(Not finished)_ **[@promptbook/wizzard](https://www.npmjs.com/package/@promptbook/wizzard)** - Wizard for creating+running promptbooks in single line\n-   **[@promptbook/execute-javascript](https://www.npmjs.com/package/@promptbook/execute-javascript)** - Execution tools for javascript inside promptbooks\n-   **[@promptbook/openai](https://www.npmjs.com/package/@promptbook/openai)** - Execution tools for OpenAI API, wrapper around OpenAI SDK\n-   **[@promptbook/anthropic-claude](https://www.npmjs.com/package/@promptbook/anthropic-claude)** - Execution tools for Anthropic Claude API, wrapper around Anthropic Claude SDK \n-   **[@promptbook/azure-openai](https://www.npmjs.com/package/@promptbook/azure-openai)** - Execution tools for Azure OpenAI API\n-   **[@promptbook/langtail](https://www.npmjs.com/package/@promptbook/langtail)** - Execution tools for Langtail API, wrapper around Langtail SDK\n-   **[@promptbook/fake-llm](https://www.npmjs.com/package/@promptbook/fake-llm)** - Mocked execution tools for testing the library and saving the tokens\n-   **[@promptbook/remote-client](https://www.npmjs.com/package/@promptbook/remote-client)** - Remote client for remote execution of promptbooks\n-   **[@promptbook/remote-server](https://www.npmjs.com/package/@promptbook/remote-server)** - Remote server for remote execution of promptbooks\n-   **[@promptbook/types](https://www.npmjs.com/package/@promptbook/types)** - Just typescript types used in the library\n-   **[@promptbook/cli](https://www.npmjs.com/package/@promptbook/cli)** - Command line interface utilities for promptbooks\n\n\n\n## 📚 Dictionary\n\nThe following glossary is used to clarify certain basic concepts:\n\n### Prompt\n\nPrompt in a text along with model requirements, but without any execution or templating logic.\n\nFor example:\n\n```json\n{\n    \"request\": \"Which sound does a cat make?\",\n    \"modelRequirements\": {\n        \"variant\": \"CHAT\"\n    }\n}\n```\n\n```json\n{\n    \"request\": \"I am a cat.\\nI like to eat fish.\\nI like to sleep.\\nI like to play with a ball.\\nI l\",\n    \"modelRequirements\": {\n        \"variant\": \"COMPLETION\"\n    }\n}\n```\n\n### Prompt Template\n\nSimilar concept to Prompt, but with templating logic.\n\nFor example:\n\n```json\n{\n    \"request\": \"Which sound does a {animalName} make?\",\n    \"modelRequirements\": {\n        \"variant\": \"CHAT\"\n    }\n}\n```\n\n### Model Requirements\n\nAbstract way to specify the LLM.\nIt does not specify the LLM with concrete version itself, only the requirements for the LLM.\n_NOT chatgpt-3.5-turbo BUT CHAT variant of GPT-3.5._\n\nFor example:\n\n```json\n{\n    \"variant\": \"CHAT\",\n    \"version\": \"GPT-3.5\",\n    \"temperature\": 0.7\n}\n```\n\n### Block type\n\nEach block of promptbook can have a different execution type.\nIt is specified in list of requirements for the block.\nBy default, it is `Prompt template`\n\n-   _(default)_ `Prompt template` The block is a prompt template and is executed by LLM (OpenAI, Azure,...)\n-   `SIMPLE TEMPLATE` The block is a simple text template which is just filled with parameters\n-   `Script` The block is a script that is executed by some script runtime, the runtime is determined by block type, currently only `javascript` is supported but we plan to add `python` and `typescript` in the future.\n-   `PROMPT DIALOG` Ask user for input\n\n### Parameters\n\nParameters that are placed in the prompt template and replaced to create the prompt.\nIt is a simple key-value object.\n\n```json\n{\n    \"animalName\": \"cat\",\n    \"animalSound\": \"Meow!\"\n}\n```\n\nThere are three types of template parameters, depending on how they are used in the promptbook:\n\n-   **INPUT PARAMETER**s are required to execute the promptbook.\n-   **Intermediate parameters** are used internally in the promptbook.\n-   **OUTPUT PARAMETER**s are explicitelly marked and they are returned as the result of the promptbook execution.\n\n_Note: Parameter can be both intermedite and output at the same time._\n\n### Promptbook\n\nPromptbook is **core concept of this library**.\nIt represents a series of prompt templates chained together to form a **pipeline** / one big prompt template with input and result parameters.\n\nInternally it can have multiple formats:\n\n-   **.ptbk.md file** in custom markdown format described above\n-   _(concept)_ **.ptbk** format, custom fileextension based on markdown\n-   _(internal)_ **JSON** format, parsed from the .ptbk.md file\n\n### Promptbook **Library**\n\nLibrary of all promptbooks used in your application.\nEach promptbook is a separate `.ptbk.md` file with unique `PIPELINE URL`. Theese urls are used to reference promptbooks in other promptbooks or in the application code.\n\n### Prompt Result\n\nPrompt result is the simplest concept of execution.\nIt is the result of executing one prompt _(NOT a template)_.\n\nFor example:\n\n```json\n{\n    \"response\": \"Meow!\",\n    \"model\": \"chatgpt-3.5-turbo\"\n}\n```\n\n### Execution Tools\n\n\n\n`ExecutionTools` is an interface which contains all the tools needed to execute prompts.\nIt contais 3 subtools:\n\n-   `LlmExecutionTools`\n-   `ScriptExecutionTools`\n-   `UserInterfaceTools`\n\nWhich are described below:\n\n#### LLM Execution Tools\n\n`LlmExecutionTools` is a container for all the tools needed to execute prompts to large language models like GPT-4.\nOn its interface it exposes common methods for prompt execution.\nInternally it calls OpenAI, Azure, GPU, proxy, cache, logging,...\n\n`LlmExecutionTools` an abstract interface that is implemented by concrete execution tools:\n\n-   `OpenAiExecutionTools`\n-   `AnthropicClaudeExecutionTools`\n-   `AzureOpenAiExecutionTools`\n-   `LangtailExecutionTools`\n-   _(Not implemented yet)_ `BardExecutionTools`\n-   _(Not implemented yet)_ `LamaExecutionTools`\n-   _(Not implemented yet)_ `GpuExecutionTools`\n-   Special case are `RemoteLlmExecutionTools` that connect to a remote server and run one of the above execution tools on that server.\n-   Another special case is `MockedEchoLlmExecutionTools` that is used for testing and mocking.\n-   The another special case is `LogLlmExecutionToolsWrapper` that is technically also an execution tools but it is more proxy wrapper around other execution tools that logs all calls to execution tools.\n\n#### Script Execution Tools\n\n`ScriptExecutionTools` is an abstract container that represents all the tools needed to EXECUTE SCRIPTs. It is implemented by concrete execution tools:\n\n-   `JavascriptExecutionTools` is a wrapper around `vm2` module that executes javascript code in a sandbox.\n-   `JavascriptEvalExecutionTools` is wrapper around `eval` function that executes javascript. It is used for testing and mocking **NOT intended to use in the production** due to its unsafe nature, use `JavascriptExecutionTools` instead.\n-   _(Not implemented yet)_ `TypescriptExecutionTools` executes typescript code in a sandbox.\n-   _(Not implemented yet)_ `PythonExecutionTools` executes python code in a sandbox.\n\nThere are [postprocessing functions](#postprocessing-functions) that can be used to postprocess the result.\n\n#### User Interface Tools\n\n`UserInterfaceTools` is an abstract container that represents all the tools needed to interact with the user. It is implemented by concrete execution tools:\n\n-   _(Not implemented yet)_ `ConsoleInterfaceTools` is a wrapper around `readline` module that interacts with the user via console.\n-   `SimplePromptInterfaceTools` is a wrapper around `window.prompt` synchronous function that interacts with the user via browser prompt. It is used for testing and mocking **NOT intended to use in the production** due to its synchronous nature.\n-   `CallbackInterfaceTools` delagates the user interaction to a async callback function. You need to provide your own implementation of this callback function and its bind to UI. \n\n### Executor\n\nExecutor is a simple async function that takes **input parameters** and returns **output parameters**.\nIt is constructed by combining execution tools and promptbook to execute together.\n\n### 🃏 Jokers (conditions)\n\nJoker is a previously defined parameter that is used to bypass some parts of the pipeline.\nIf the joker is present in the template, it is checked to see if it meets the requirements (without postprocessing), and if so, it is used instead of executing that prompt template. There can be multiple wildcards in a prompt template, if so they are checked in order and the first one that meets the requirements is used.\n\nIf none of the jokers meet the requirements, the prompt template is executed as usual.\n\nThis can be useful, for example, if you want to use some predefined data, or if you want to use some data from the user, but you are not sure if it is suitable form.\n\nWhen using wildcards, you must have at least one minimum expectation. If you do not have a minimum expectation, the joker will always fulfil the expectation because it has none, so it makes no logical sense.\n\nLook at [jokers.ptbk.md](samples/templates/41-jokers.ptbk.md) sample.\n\n### Postprocessing functions\n\nYou can define postprocessing functions when creating `JavascriptEvalExecutionTools`:\n\n```\n\n```\n\nAdditionally there are some usefull string-manipulation build-in functions, which are [listed here](src/scripting/javascript/JavascriptEvalExecutionTools.ts).\n\n### Expectations\n\n`Expect` command describes the desired output of the prompt template (after post-processing)\nIt can set limits for the maximum/minimum length of the output, measured in characters, words, sentences, paragraphs,...\n\n_Note: LLMs work with tokens, not characters, but in Promptbooks we want to use some human-recognisable and cross-model interoperable units._\n\n```markdown\n# ✨ Sample: Expectations\n\n-   INPUT  PARAMETER {yourName} Name of the hero\n\n## 💬 Question\n\n-   EXPECT MAX 30 CHARACTERS\n-   EXPECT MIN 2 CHARACTERS\n-   EXPECT MAX 3 WORDS\n-   EXPECT EXACTLY 1 SENTENCE\n-   EXPECT EXACTLY 1 LINE\n\n...\n```\n\nThere are two types of expectations which are not strictly symmetrical:\n\n#### Minimal expectations\n\n-   `EXPECT MIN 0 ...` is not valid minimal expectation. It makes no sense.\n-   `EXPECT JSON` is both minimal and maximal expectation\n-   When you are using `JOKER` in same prompt template, you need to have at least one minimal expectation\n\n#### Maximal expectations\n\n-   `EXPECT MAX 0 ...` is valid maximal expectation. For example, you can expect 0 pages and 2 sentences.\n-   `EXPECT JSON` is both minimal and maximal expectation\n\nLook at [expectations.ptbk.md](samples/templates/45-expectations.ptbk.md) and [expect-json.ptbk.md](samples/templates/45-expect-json.ptbk.md) samples for more.\n\n### Execution report\n\nExecution report is a simple object or markdown that contains information about the execution of the pipeline.\n\n[See the example of such a report](/samples/templates/50-advanced.report.md)\n\n\n\n\n\n### Remote server\n\nRemote server is a proxy server that uses its execution tools internally and exposes the executor interface externally.\n\nYou can simply use `RemoteExecutionTools` on client-side javascript and connect to your remote server.\nThis is useful to make all logic on browser side but not expose your API keys or no need to use customer's GPU.\n\n## 👨‍💻 Usage and integration _(for developers)_\n\n\n\n### 🔌 Usage in Typescript / Javascript\n\n-   [Simple usage](./samples/usage/simple-script)\n-   [Usage with client and remote server](./samples/usage/remote)\n\n## ➕➖ When to use Promptbook?\n\n### ➕ When to use\n\n-   When you are writing app that generates complex things via LLM - like **websites, articles, presentations, code, stories, songs**,...\n-   When you want to **separate code from text prompts**\n-   When you want to describe **complex prompt pipelines** and don't want to do it in the code\n-   When you want to **orchestrate multiple prompts** together\n-   When you want to **reuse** parts of prompts in multiple places\n-   When you want to **version** your prompts and **test multiple versions**\n-   When you want to **log** the execution of prompts and backtrace the issues\n\n### ➖ When not to use\n\n-   When you are writing just a simple chatbot without any extra logic, just system messages\n\n## 🐜 Known issues\n\n\n\n## 🧼 Intentionally not implemented features\n\n\n\n## ❔ FAQ\n\nIf you have a question [start a discussion](https://github.com/webgptorg/promptbook/discussions/), [open an issue](https://github.com/webgptorg/promptbook/issues) or [write me an email](https://www.pavolhejny.com/contact).\n\n### Why not just use the OpenAI SDK / Anthropic Claude SDK / ...?\n\nDifferent levels of abstraction. OpenAI library is for direct use of OpenAI API. This library is for a higher level of abstraction. It is for creating prompt templates and promptbooks that are independent of the underlying library, LLM model, or even LLM provider.\n\n### How is it different from the Langchain library?\n\nLangchain is primarily aimed at ML developers working in Python. This library is for developers working in javascript/typescript and creating applications for end users.\n\nWe are considering creating a bridge/converter between these two libraries.\n\n\n\n### Promptbooks vs. OpenAI`s GPTs\n\nGPTs are chat assistants that can be assigned to specific tasks and materials. But they are still chat assistants. Promptbooks are a way to orchestrate many more predefined tasks to have much tighter control over the process. Promptbooks are not a good technology for creating human-like chatbots, GPTs are not a good technology for creating outputs with specific requirements.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n### Where should I store my promptbooks?\n\nIf you use raw SDKs, you just put prompts in the sourcecode, mixed in with typescript, javascript, python or whatever programming language you use.\n\nIf you use promptbooks, you can store them in several places, each with its own advantages and disadvantages:\n\n1. As **source code**, typically git-committed. In this case you can use the versioning system and the promptbooks will be tightly coupled with the version of the application. You still get the power of promptbooks, as you separate the concerns of the prompt-engineer and the programmer.\n\n2. As data in a **database** In this case, promptbooks are like posts / articles on the blog. They can be modified independently of the application. You don't need to redeploy the application to change the promptbooks. You can have multiple versions of promptbooks for each user. You can have a web interface for non-programmers to create and modify promptbooks. But you lose the versioning system and you still have to consider the interface between the promptbooks and the application _(= input and output parameters)_.\n\n3. In a **configuration** in environment variables. This is a good way to store promptbooks if you have an application with multiple deployments and you want to have different but simple promptbooks for each deployment and you don't need to change them often.\n\n### What should I do when I need same promptbook in multiple human languages?\n\nA single promptbook can be written for several _(human)_ languages at once. However, we recommend that you have separate promptbooks for each language.\n\nIn large language models, you will get better results if you have prompts in the same language as the user input.\n\nThe best way to manage this is to have suffixed promptbooks like `write-website-content.en.ptbk.md` and `write-website-content.cs.ptbk.md` for each supported language.\n\n\n\n\n\n## ⌚ Changelog\n\nSee [CHANGELOG.md](./CHANGELOG.md)\n\n## 📜 License\n\n<p xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:dct=\"http://purl.org/dc/terms/\"><a property=\"dct:title\" rel=\"cc:attributionURL\" href=\"https://github.com/webgptorg/promptbook\">Promptbook</a> by <a rel=\"cc:attributionURL dct:creator\" property=\"cc:attributionName\" href=\"https://github.com/hejny/\">Pavol Hejný</a> is licensed under <a href=\"https://creativecommons.org/licenses/by/4.0/?ref=chooser-v1\" target=\"_blank\" rel=\"license noopener noreferrer\" style=\"display:inline-block;\">CC BY 4.0</a></p>\n\n## 🎯 Todos\n\nSee [TODO.md](./TODO.md)\n\n\n\n\n## 🖋️ Contributing\n\nI am open to pull requests, feedback, and suggestions. Or if you like this utility, you can [☕ buy me a coffee](https://www.buymeacoffee.com/hejny) or [donate via cryptocurrencies](https://github.com/hejny/hejny/blob/main/documents/crypto.md).\n\nYou can also ⭐ star the promptbook package, [follow me on GitHub](https://github.com/hejny) or [various other social networks](https://www.pavolhejny.com/contact/).","publish_time":1711394971420,"maintainers":[{"name":"hejny","email":"pavol@hejny.org"}],"_cnpm_publish_time":1711394971420,"dist-tags":{"latest":"0.114.0-50","legacy":"0.114.0-51"}}