@promptbook/utils 0.44.0-9 โ†’ 0.45.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 (58) hide show
  1. package/README.md +862 -2
  2. package/esm/index.es.js +7 -3
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/_packages/utils.index.d.ts +4 -2
  5. package/esm/typings/conversion/promptbookStringToJson.d.ts +2 -2
  6. package/esm/typings/execution/ExecutionTools.d.ts +3 -3
  7. package/esm/typings/execution/NaturalExecutionTools.d.ts +2 -2
  8. package/esm/typings/execution/ScriptExecutionTools.d.ts +2 -2
  9. package/esm/typings/execution/UserInterfaceTools.d.ts +1 -1
  10. package/esm/typings/execution/plugins/natural-execution-tools/langtail/LangtailExecutionTools.d.ts +10 -0
  11. package/esm/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +6 -2
  12. package/esm/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionTools.d.ts +5 -0
  13. package/esm/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +7 -7
  14. package/esm/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionToolsOptions.d.ts +1 -1
  15. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +5 -1
  16. package/esm/typings/execution/plugins/script-execution-tools/javascript/utils/unknownToString.d.ts +7 -0
  17. package/esm/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceToolsOptions.d.ts +3 -3
  18. package/esm/typings/execution/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +1 -1
  19. package/esm/typings/library/PromptbookLibrary.d.ts +1 -1
  20. package/esm/typings/types/ExecutionTypes.d.ts +1 -1
  21. package/esm/typings/types/ModelRequirements.d.ts +1 -1
  22. package/esm/typings/types/Prompt.d.ts +5 -0
  23. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +6 -5
  24. package/esm/typings/types/PromptbookJson/PromptTemplateParameterJson.d.ts +1 -1
  25. package/esm/typings/types/PromptbookJson/PromptbookJson.d.ts +3 -3
  26. package/esm/typings/types/ScriptLanguage.d.ts +1 -1
  27. package/esm/typings/types/TaskProgress.d.ts +2 -2
  28. package/esm/typings/types/execution-report/ExecutionReportStringOptions.d.ts +1 -1
  29. package/esm/typings/utils/markdown/extractAllBlocksFromMarkdown.d.ts +1 -1
  30. package/package.json +3 -3
  31. package/umd/index.umd.js +50 -44
  32. package/umd/index.umd.js.map +1 -1
  33. package/umd/typings/_packages/utils.index.d.ts +4 -2
  34. package/umd/typings/conversion/promptbookStringToJson.d.ts +2 -2
  35. package/umd/typings/execution/ExecutionTools.d.ts +3 -3
  36. package/umd/typings/execution/NaturalExecutionTools.d.ts +2 -2
  37. package/umd/typings/execution/ScriptExecutionTools.d.ts +2 -2
  38. package/umd/typings/execution/UserInterfaceTools.d.ts +1 -1
  39. package/umd/typings/execution/plugins/natural-execution-tools/langtail/LangtailExecutionTools.d.ts +10 -0
  40. package/umd/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +6 -2
  41. package/umd/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionTools.d.ts +5 -0
  42. package/umd/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +7 -7
  43. package/umd/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionToolsOptions.d.ts +1 -1
  44. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +5 -1
  45. package/umd/typings/execution/plugins/script-execution-tools/javascript/utils/unknownToString.d.ts +7 -0
  46. package/umd/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceToolsOptions.d.ts +3 -3
  47. package/umd/typings/execution/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +1 -1
  48. package/umd/typings/library/PromptbookLibrary.d.ts +1 -1
  49. package/umd/typings/types/ExecutionTypes.d.ts +1 -1
  50. package/umd/typings/types/ModelRequirements.d.ts +1 -1
  51. package/umd/typings/types/Prompt.d.ts +5 -0
  52. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +6 -5
  53. package/umd/typings/types/PromptbookJson/PromptTemplateParameterJson.d.ts +1 -1
  54. package/umd/typings/types/PromptbookJson/PromptbookJson.d.ts +3 -3
  55. package/umd/typings/types/ScriptLanguage.d.ts +1 -1
  56. package/umd/typings/types/TaskProgress.d.ts +2 -2
  57. package/umd/typings/types/execution-report/ExecutionReportStringOptions.d.ts +1 -1
  58. package/umd/typings/utils/markdown/extractAllBlocksFromMarkdown.d.ts +1 -1
package/README.md CHANGED
@@ -1,5 +1,865 @@
1
- # ๐Ÿ“– Promptbook
1
+ # ![Promptbook logo - cube with letters P and B](./other/design/logo-h1.png) Promptbook
2
2
 
3
3
  Library to supercharge your use of large language models
4
4
 
5
- [Read the manual](https://github.com/webgptorg/promptbook)
5
+ <!--Badges-->
6
+ <!--โš ๏ธWARNING: This section was generated by https://github.com/hejny/batch-project-editor/blob/main/src/workflows/800-badges/badges.ts so every manual change will be overwritten.-->
7
+
8
+ [![License of ๐Ÿ“– Prompt book](https://img.shields.io/github/license/webgptorg/promptbook.svg?style=flat)](https://github.com/webgptorg/promptbook/blob/main/LICENSE)
9
+ [![Known Vulnerabilities](https://snyk.io/test/github/webgptorg/promptbook/badge.svg)](https://snyk.io/test/github/webgptorg/promptbook)
10
+ [![Issues](https://img.shields.io/github/issues/webgptorg/promptbook.svg?style=flat)](https://github.com/webgptorg/promptbook/issues)
11
+ [![Socket Badge](https://socket.dev/api/badge/npm/package/@promptbook/utils)](https://socket.dev/npm/package/@promptbook/utils)
12
+
13
+ <!--/Badges-->
14
+
15
+ ## ๐Ÿ“ฆ Package `@promptbook/utils`
16
+
17
+ - Promptbooks are [divided into several](#-packages) packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook).
18
+ - This package `@promptbook/utils` is one part of the promptbook ecosystem.
19
+
20
+ To install this package, run:
21
+
22
+ ```bash
23
+ npm i @promptbook/utils
24
+ ```
25
+
26
+ Utility functions used in the library but also useful for individual use in preprocessing and postprocessing LLM inputs and outputs
27
+
28
+ Here is a overview of the functions which are exported from the `@promptbook/utils` package and can be used in your own projects:
29
+
30
+ ## Postprocessing
31
+
32
+ Sometimes 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:
33
+
34
+ `spaceTrim`,
35
+ `extractAllBlocksFromMarkdown`, <!-- <- [๐ŸŒป] -->
36
+ `extractAllListItemsFromMarkdown`,
37
+ `extractBlock` ,<!-- <- [๐ŸŒป] -->
38
+ `extractOneBlockFromMarkdown`,
39
+ `prettifyPromptbookString`,
40
+ `removeContentComments`,
41
+ `removeEmojis`,
42
+ `removeMarkdownFormatting`,
43
+ `removeQuotes`,
44
+ `trimCodeBlock`,
45
+ `trimEndOfCodeBlock`,
46
+ `unwrapResult`
47
+
48
+ Very often you will use `unwrapResult`, which is used to extract the result you need from output with some additional information:
49
+
50
+ ```typescript
51
+ import { unwrapResult } from '@promptbook/utils';
52
+
53
+ unwrapResult('Best greeting for the user is "Hi Pavol!"'); // 'Hi Pavol!'
54
+ ```
55
+
56
+ ## Templating
57
+
58
+ There is a function `replaceParameters` which is used to replace the parameters in given template optimized to LLM prompt templates.
59
+
60
+ ```typescript
61
+ import { replaceParameters } from '@promptbook/utils';
62
+
63
+ replaceParameters('Hello, {name}!', { name: 'world' }); // 'Hello, world!'
64
+ ```
65
+
66
+ And also multiline templates with blockquotes
67
+
68
+ ```typescript
69
+ import { replaceParameters, spaceTrim } from '@promptbook/utils';
70
+
71
+ replaceParameters(
72
+ spaceTrim(`
73
+ Hello, {name}!
74
+
75
+ > {answer}
76
+ `),
77
+ {
78
+ name: 'world',
79
+ answer: spaceTrim(`
80
+ I'm fine,
81
+ thank you!
82
+
83
+ And you?
84
+ `),
85
+ },
86
+ );
87
+
88
+ // Hello, world!
89
+ //
90
+ // > I'm fine,
91
+ // > thank you!
92
+ // >
93
+ // > And you?
94
+ ```
95
+
96
+ ## Counting
97
+
98
+ Theese functions are usefull to count stats about the input/output in human-like terms not tokens and bytes, you can use
99
+ `countCharacters`, `countLines`, `countPages`, `countParagraphs`, `countSentences`, `countWords`
100
+
101
+ ```typescript
102
+ import { countWords } from '@promptbook/utils';
103
+
104
+ console.log(countWords('Hello, world!')); // 2
105
+ ```
106
+
107
+ ## Splitting
108
+
109
+ Splitting functions are similar to counting but they return the splitted parts of the input/output, you can use
110
+ `splitIntoCharacters`, `splitIntoLines`, `splitIntoPages`, `splitIntoParagraphs`, `splitIntoSentences`, `splitIntoWords`
111
+
112
+ ```typescript
113
+ import { splitIntoWords } from '@promptbook/utils';
114
+
115
+ console.log(splitIntoWords('Hello, world!')); // ['Hello', 'world']
116
+ ```
117
+
118
+ ## Normalization
119
+
120
+ Normalization functions are used to put the string into a normalized form, you can use
121
+ `kebab-case`
122
+ `PascalCase`
123
+ `SCREAMING_CASE`
124
+ `snake_case`
125
+ `kebab-case`
126
+
127
+ ```typescript
128
+ import { normalizeTo } from '@promptbook/utils';
129
+
130
+ console.log(normalizeTo['kebab-case']('Hello, world!')); // 'hello-world'
131
+ ```
132
+
133
+ - There are more normalization functions like `capitalize`, `decapitalize`, `removeDiacritics`,...
134
+ - Theese can be also used as postprocessing functions in the `POSTPROCESS` command in promptbook
135
+
136
+ ## Misc
137
+
138
+ See 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.
139
+
140
+ <!-- TODO: Describe -->
141
+
142
+ `assertsExecutionSuccessful`,
143
+ `checkExpectations`,
144
+ `executionReportJsonToString`,
145
+ `isPassingExpectations`,
146
+ `isValidJsonString`,
147
+ `parseNumber` <!-- <- [๐ŸŒป] -->
148
+
149
+
150
+ ---
151
+
152
+ Rest of the documentation is common for **entire promptbook ecosystem**:
153
+
154
+ <!--
155
+ TODO: Probbably remove this section only in packages
156
+ > โš  Warning: This library is still in early development.
157
+ -->
158
+
159
+ ## ๐Ÿค Whitepaper
160
+
161
+ When 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.
162
+
163
+ If you need something more advanced or want to extend the capabilities of LLMs, you generally have three ways to proceed:
164
+
165
+ 1. **Fine-tune** the model to your specifications or even train your own.
166
+ 2. **Prompt-engineer** the prompt to the best shape you can achieve.
167
+ 3. Use **multiple prompts** in a pipeline to get the best result.
168
+
169
+ In any of these situations, but especially in (3), the Promptbook library can make your life easier and make **orchestraror for your prompts**.
170
+
171
+ - **Separation of concerns** between prompt engineer and programmer; between code files and prompt files; and between prompts, templates, templating pipelines, and their execution logic.
172
+ - Set up a **common format** for prompts that is interchangeable between projects and language/technology stacks.
173
+ - **Preprocessing** and cleaning the input data from the user.
174
+ - Use default values - **Jokers** to bypass some parts of the pipeline.
175
+ - **Expect** some specific output from the model.
176
+ - **Retry** mismatched outputs.
177
+ - **Combine** multiple models together.
178
+ - Interactive **User interaction** with the model and the user.
179
+ - Leverage **external** sources (like ChatGPT plugins or OpenAI's GPTs).
180
+ - Simplify your code to be **DRY** and not repeat all the boilerplate code for each prompt.
181
+ - **Versioning** of promptbooks
182
+ - **Reuse** parts of promptbooks in/between projects.
183
+ - Run the LLM **optimally** in parallel, with the best _cost/quality_ ratio or _speed/quality_ ratio.
184
+ - **Execution report** to see what happened during the execution.
185
+ - **Logging** the results of the promptbooks.
186
+ - _(Not ready yet)_ **Caching** calls to LLMs to save money and time.
187
+ - _(Not ready yet)_ Extend one prompt book from another one.
188
+ - _(Not ready yet)_ Leverage the **streaming** to make super cool UI/UX.
189
+ - _(Not ready yet)_ **A/B testing** to determine which prompt works best for the job.
190
+
191
+ ![WebGPT](./other/screencasts/screencast-fiabciakcmgepblmdkmemdbbkilneeeh-2023.10.26-21_46_17.gif)
192
+
193
+ ## ๐Ÿง” Promptbook _(for prompt-engeneers)_
194
+
195
+ **P**romp**t** **b**oo**k** markdown file (**PTBK** for short, or `.ptbk.md`) is document that describes a series of prompts that are chained together to form somewhat reciepe for transforming natural language input. Inside a PTBK you can use chat prompts, completion prompts, scripting or trigger interaction with user to ask for additional information.
196
+
197
+ - Multiple promptbooks forms a library which will become a **part of your application codebase**.
198
+ - Theese promptbooks are designed such as they **can be written by non-programmers**.
199
+
200
+ <!-- TODO: [๐Ÿง ] Make some more clear escaping -->
201
+
202
+ ### Sample:
203
+
204
+ File `write-website-content.ptbk.md`:
205
+
206
+ <!------------------------[ Sample: ]------------------------>
207
+
208
+ > # ๐ŸŒ Create website content
209
+ >
210
+ > Instructions for creating web page content.
211
+ >
212
+ > - PROMPTBOOK URL https://promptbook.webgpt.com/en/write-website-content.ptbk.md@v0.1.0
213
+ > - PROMPTBOOK VERSION 0.0.1
214
+ > - INPUTโ€ฏโ€ฏPARAM `{rawTitle}` Automatically suggested a site name or empty text
215
+ > - INPUTโ€ฏโ€ฏPARAM `{rawAssigment}` Automatically generated site entry from image recognition
216
+ > - OUTPUTโ€ฏPARAM `{content}` Web content
217
+ > - OUTPUTโ€ฏPARAM `{keywords}` Keywords
218
+ >
219
+ > ## ๐Ÿ‘ค Specifying the assigment
220
+ >
221
+ > What is your web about?
222
+ >
223
+ > - PROMPT DIALOG
224
+ >
225
+ > ```
226
+ > {rawAssigment}
227
+ > ```
228
+ >
229
+ > `-> {assigment}` Website assignment and specification
230
+ >
231
+ > ## โœจ Improving the title
232
+ >
233
+ > - MODEL VARIANT Chat
234
+ > - MODEL NAME `gpt-4`
235
+ > - POSTPROCESSING `unwrapResult`
236
+ >
237
+ > ```
238
+ > As an experienced marketing specialist, you have been entrusted with improving the name of your client's business.
239
+ >
240
+ > A suggested name from a client:
241
+ > "{rawTitle}"
242
+ >
243
+ > Assignment from customer:
244
+ >
245
+ > > {assigment}
246
+ >
247
+ > ## Instructions:
248
+ >
249
+ > - Write only one name suggestion
250
+ > - The name will be used on the website, business cards, visuals, etc.
251
+ > ```
252
+ >
253
+ > `-> {enhancedTitle}` Enhanced title
254
+ >
255
+ > ## ๐Ÿ‘ค Website title approval
256
+ >
257
+ > Is the title for your website okay?
258
+ >
259
+ > - PROMPT DIALOG
260
+ >
261
+ > ```
262
+ > {enhancedTitle}
263
+ > ```
264
+ >
265
+ > `-> {title}` Title for the website
266
+ >
267
+ > ## ๐Ÿฐ Cunning subtitle
268
+ >
269
+ > - MODEL VARIANT Chat
270
+ > - MODEL NAME `gpt-4`
271
+ > - POSTPROCESSING `unwrapResult`
272
+ >
273
+ > ```
274
+ > As an experienced copywriter, you have been entrusted with creating a claim for the "{title}" web page.
275
+ >
276
+ > A website assignment from a customer:
277
+ >
278
+ > > {assigment}
279
+ >
280
+ > ## Instructions:
281
+ >
282
+ > - Write only one name suggestion
283
+ > - Claim will be used on website, business cards, visuals, etc.
284
+ > - Claim should be punchy, funny, original
285
+ > ```
286
+ >
287
+ > `-> {claim}` Claim for the web
288
+ >
289
+ > ## ๐Ÿšฆ Keyword analysis
290
+ >
291
+ > - MODEL VARIANT Chat
292
+ > - MODEL NAME `gpt-4`
293
+ >
294
+ > ```
295
+ > As an experienced SEO specialist, you have been entrusted with creating keywords for the website "{title}".
296
+ >
297
+ > Website assignment from the customer:
298
+ >
299
+ > > {assigment}
300
+ >
301
+ > ## Instructions:
302
+ >
303
+ > - Write a list of keywords
304
+ > - Keywords are in basic form
305
+ >
306
+ > ## Example:
307
+ >
308
+ > - Ice cream
309
+ > - Olomouc
310
+ > - Quality
311
+ > - Family
312
+ > - Tradition
313
+ > - Italy
314
+ > - Craft
315
+ >
316
+ > ```
317
+ >
318
+ > `-> {keywords}` Keywords
319
+ >
320
+ > ## ๐Ÿ”— Combine the beginning
321
+ >
322
+ > - SIMPLE TEMPLATE
323
+ >
324
+ > ```
325
+ >
326
+ > # {title}
327
+ >
328
+ > > {claim}
329
+ >
330
+ > ```
331
+ >
332
+ > `-> {contentBeginning}` Beginning of web content
333
+ >
334
+ > ## ๐Ÿ–‹ Write the content
335
+ >
336
+ > - MODEL VARIANT Completion
337
+ > - MODEL NAME `gpt-3.5-turbo-instruct`
338
+ >
339
+ > ```
340
+ > As an experienced copywriter and web designer, you have been entrusted with creating text for a new website {title}.
341
+ >
342
+ > A website assignment from a customer:
343
+ >
344
+ > > {assigment}
345
+ >
346
+ > ## Instructions:
347
+ >
348
+ > - Text formatting is in Markdown
349
+ > - Be concise and to the point
350
+ > - Use keywords, but they should be naturally in the text
351
+ > - This is the complete content of the page, so don't forget all the important information and elements the page should contain
352
+ > - Use headings, bullets, text formatting
353
+ >
354
+ > ## Keywords:
355
+ >
356
+ > {keywords}
357
+ >
358
+ > ## Web Content:
359
+ >
360
+ > {contentBeginning}
361
+ > ```
362
+ >
363
+ > `-> {contentBody}` Middle of the web content
364
+ >
365
+ > ## ๐Ÿ”— Combine the content
366
+ >
367
+ > - SIMPLE TEMPLATE
368
+ >
369
+ > ```markdown
370
+ > {contentBeginning}
371
+ >
372
+ > {contentBody}
373
+ > ```
374
+ >
375
+ > `-> {content}`
376
+
377
+ <!------------------------[ /Sample ]------------------------>
378
+
379
+ Following is the scheme how the promptbook above is executed:
380
+
381
+ ```mermaid
382
+ %% ๐Ÿ”ฎ Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually
383
+
384
+ flowchart LR
385
+ subgraph "๐ŸŒ Create website content"
386
+
387
+ direction TB
388
+
389
+ input((Input)):::input
390
+ templateSpecifyingTheAssigment(๐Ÿ‘ค Specifying the assigment)
391
+ input--"{rawAssigment}"-->templateSpecifyingTheAssigment
392
+ templateImprovingTheTitle(โœจ Improving the title)
393
+ input--"{rawTitle}"-->templateImprovingTheTitle
394
+ templateSpecifyingTheAssigment--"{assigment}"-->templateImprovingTheTitle
395
+ templateWebsiteTitleApproval(๐Ÿ‘ค Website title approval)
396
+ templateImprovingTheTitle--"{enhancedTitle}"-->templateWebsiteTitleApproval
397
+ templateCunningSubtitle(๐Ÿฐ Cunning subtitle)
398
+ templateWebsiteTitleApproval--"{title}"-->templateCunningSubtitle
399
+ templateSpecifyingTheAssigment--"{assigment}"-->templateCunningSubtitle
400
+ templateKeywordAnalysis(๐Ÿšฆ Keyword analysis)
401
+ templateWebsiteTitleApproval--"{title}"-->templateKeywordAnalysis
402
+ templateSpecifyingTheAssigment--"{assigment}"-->templateKeywordAnalysis
403
+ templateCombineTheBeginning(๐Ÿ”— Combine the beginning)
404
+ templateWebsiteTitleApproval--"{title}"-->templateCombineTheBeginning
405
+ templateCunningSubtitle--"{claim}"-->templateCombineTheBeginning
406
+ templateWriteTheContent(๐Ÿ–‹ Write the content)
407
+ templateWebsiteTitleApproval--"{title}"-->templateWriteTheContent
408
+ templateSpecifyingTheAssigment--"{assigment}"-->templateWriteTheContent
409
+ templateKeywordAnalysis--"{keywords}"-->templateWriteTheContent
410
+ templateCombineTheBeginning--"{contentBeginning}"-->templateWriteTheContent
411
+ templateCombineTheContent(๐Ÿ”— Combine the content)
412
+ templateCombineTheBeginning--"{contentBeginning}"-->templateCombineTheContent
413
+ templateWriteTheContent--"{contentBody}"-->templateCombineTheContent
414
+
415
+ templateCombineTheContent--"{content}"-->output
416
+ output((Output)):::output
417
+
418
+ classDef input color: grey;
419
+ classDef output color: grey;
420
+
421
+ end;
422
+ ```
423
+
424
+ [More template samples](./samples/templates/)
425
+
426
+ _Note: We are using [postprocessing functions](#postprocessing-functions) like `unwrapResult` that can be used to postprocess the result._
427
+
428
+ ## ๐Ÿ“ฆ Packages
429
+
430
+ This library is divided into several packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook):
431
+
432
+ <!--[๐Ÿ” ]-->
433
+
434
+ - **[@promptbook/core](https://www.npmjs.com/package/@promptbook/core)** - Core of the library, it contains the main logic for promptbooks
435
+ - โญ **[@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
436
+ - _(Not finished)_ **[@promptbook/wizzard](https://www.npmjs.com/package/@promptbook/wizzard)** - Wizard for creating+running promptbooks in single line
437
+ - **[@promptbook/execute-javascript](https://www.npmjs.com/package/@promptbook/execute-javascript)** - Execution tools for javascript inside promptbooks
438
+ - **[@promptbook/openai](https://www.npmjs.com/package/@promptbook/openai)** - Execution tools for OpenAI API, wrapper around OpenAI SDK
439
+ - **[@promptbook/remote-client](https://www.npmjs.com/package/@promptbook/remote-client)** - Remote client for remote execution of promptbooks
440
+ - **[@promptbook/remote-server](https://www.npmjs.com/package/@promptbook/remote-server)** - Remote server for remote execution of promptbooks
441
+ - **[@promptbook/types](https://www.npmjs.com/package/@promptbook/types)** - Just typescript types used in the library
442
+ - **[@promptbook/cli](https://www.npmjs.com/package/@promptbook/cli)** - Command line interface utilities for promptbooks
443
+
444
+ ## ๐Ÿ“š Dictionary
445
+
446
+ The following glossary is used to clarify certain basic concepts:
447
+
448
+ ### Prompt
449
+
450
+ Prompt in a text along with model requirements, but without any execution or templating logic.
451
+
452
+ For example:
453
+
454
+ ```json
455
+ {
456
+ "request": "Which sound does a cat make?",
457
+ "modelRequirements": {
458
+ "variant": "CHAT"
459
+ }
460
+ }
461
+ ```
462
+
463
+ ```json
464
+ {
465
+ "request": "I am a cat.\nI like to eat fish.\nI like to sleep.\nI like to play with a ball.\nI l",
466
+ "modelRequirements": {
467
+ "variant": "COMPLETION"
468
+ }
469
+ }
470
+ ```
471
+
472
+ ### Prompt Template
473
+
474
+ Similar concept to Prompt, but with templating logic.
475
+
476
+ For example:
477
+
478
+ ```json
479
+ {
480
+ "request": "Which sound does a {animalName} make?",
481
+ "modelRequirements": {
482
+ "variant": "CHAT"
483
+ }
484
+ }
485
+ ```
486
+
487
+ ### Model Requirements
488
+
489
+ Abstract way to specify the LLM.
490
+ It does not specify the LLM with concrete version itself, only the requirements for the LLM.
491
+ _NOT chatgpt-3.5-turbo BUT CHAT variant of GPT-3.5._
492
+
493
+ For example:
494
+
495
+ ```json
496
+ {
497
+ "variant": "CHAT",
498
+ "version": "GPT-3.5",
499
+ "temperature": 0.7
500
+ }
501
+ ```
502
+
503
+ ### Execution type
504
+
505
+ Each block of promptbook can have a different execution type.
506
+ It is specified in list of requirements for the block.
507
+ By default, it is `Prompt template`
508
+
509
+ - _(default)_ `Prompt template` The block is a prompt template and is executed by LLM (OpenAI, Azure,...)
510
+ - `SIMPLE TEMPLATE` The block is a simple text template which is just filled with parameters
511
+ - `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.
512
+ - `PROMPT DIALOG` Ask user for input
513
+
514
+ ### Parameters
515
+
516
+ Parameters that are placed in the prompt template and replaced to create the prompt.
517
+ It is a simple key-value object.
518
+
519
+ ```json
520
+ {
521
+ "animalName": "cat",
522
+ "animalSound": "Meow!"
523
+ }
524
+ ```
525
+
526
+ There are three types of template parameters, depending on how they are used in the promptbook:
527
+
528
+ - **INPUT PARAMETER**s are required to execute the promptbook.
529
+ - **Intermediate parameters** are used internally in the promptbook.
530
+ - **OUTPUT PARAMETER**s are explicitelly marked and they are returned as the result of the promptbook execution.
531
+
532
+ _Note: Parameter can be both intermedite and output at the same time._
533
+
534
+ ### Promptbook
535
+
536
+ Promptbook is **core concept of this library**.
537
+ It represents a series of prompt templates chained together to form a **pipeline** / one big prompt template with input and result parameters.
538
+
539
+ Internally it can have multiple formats:
540
+
541
+ - **.ptbk.md file** in custom markdown format described above
542
+ - _(concept)_ **.ptbk** format, custom fileextension based on markdown
543
+ - _(internal)_ **JSON** format, parsed from the .ptbk.md file
544
+
545
+ ### Promptbook **Library**
546
+
547
+ Library of all promptbooks used in your application.
548
+ Each promptbook is a separate `.ptbk.md` file with unique `PROMPTBOOK URL`. Theese urls are used to reference promptbooks in other promptbooks or in the application code.
549
+
550
+ ### Prompt Result
551
+
552
+ Prompt result is the simplest concept of execution.
553
+ It is the result of executing one prompt _(NOT a template)_.
554
+
555
+ For example:
556
+
557
+ ```json
558
+ {
559
+ "response": "Meow!",
560
+ "model": "chatgpt-3.5-turbo"
561
+ }
562
+ ```
563
+
564
+ ### Execution Tools
565
+
566
+ `ExecutionTools` is an interface which contains all the tools needed to execute prompts.
567
+ It contais 3 subtools:
568
+
569
+ - `NaturalExecutionTools`
570
+ - `ScriptExecutionTools`
571
+ - `UserInterfaceTools`
572
+
573
+ Which are described below:
574
+
575
+ #### Natural Execution Tools
576
+
577
+ `NaturalExecutionTools` is a container for all the tools needed to execute prompts to large language models like GPT-4.
578
+ On its interface it exposes common methods for prompt execution.
579
+ Internally it calls OpenAI, Azure, GPU, proxy, cache, logging,...
580
+
581
+ `NaturalExecutionTools` an abstract interface that is implemented by concrete execution tools:
582
+
583
+ - `OpenAiExecutionTools`
584
+ - _(Not implemented yet)_ `AnthropicClaudeExecutionTools`
585
+ - _(Not implemented yet)_ `AzureOpenAiExecutionTools`
586
+ - _(Not implemented yet)_ `BardExecutionTools`
587
+ - _(Not implemented yet)_ `LamaExecutionTools`
588
+ - _(Not implemented yet)_ `GpuExecutionTools`
589
+ - And a special case are `RemoteNaturalExecutionTools` that connect to a remote server and run one of the above execution tools on that server.
590
+ - The second special case is `MockedEchoNaturalExecutionTools` that is used for testing and mocking.
591
+ - The third special case is `LogNaturalExecutionToolsWrapper` that is technically also an execution tools but it is more proxy wrapper around other execution tools that logs all calls to execution tools.
592
+
593
+ #### Script Execution Tools
594
+
595
+ `ScriptExecutionTools` is an abstract container that represents all the tools needed to EXECUTE SCRIPTs. It is implemented by concrete execution tools:
596
+
597
+ - `JavascriptExecutionTools` is a wrapper around `vm2` module that executes javascript code in a sandbox.
598
+ - `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.
599
+ - _(Not implemented yet)_ `TypescriptExecutionTools` executes typescript code in a sandbox.
600
+ - _(Not implemented yet)_ `PythonExecutionTools` executes python code in a sandbox.
601
+
602
+ There are [postprocessing functions](#postprocessing-functions) that can be used to postprocess the result.
603
+
604
+ #### User Interface Tools
605
+
606
+ `UserInterfaceTools` is an abstract container that represents all the tools needed to interact with the user. It is implemented by concrete execution tools:
607
+
608
+ - _(Not implemented yet)_ `ConsoleInterfaceTools` is a wrapper around `readline` module that interacts with the user via console.
609
+ - `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.
610
+ - `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. <!-- <- TODO: Provide here a way how to do it with some our plugin -->
611
+
612
+ ### Executor
613
+
614
+ Executor is a simple async function that takes **input parameters** and returns **output parameters**.
615
+ It is constructed by combining execution tools and promptbook to execute together.
616
+
617
+ ### ๐Ÿƒ Jokers
618
+
619
+ Joker is a previously defined parameter that is used to bypass some parts of the pipeline.
620
+ If 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.
621
+
622
+ If none of the jokers meet the requirements, the prompt template is executed as usual.
623
+
624
+ This 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.
625
+
626
+ When 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.
627
+
628
+ Look at [jokers.ptbk.md](samples/templates/41-jokers.ptbk.md) sample.
629
+
630
+ ### Postprocessing functions
631
+
632
+ You can define postprocessing functions when creating `JavascriptEvalExecutionTools`:
633
+
634
+ ```
635
+
636
+ ```
637
+
638
+ Additionally there are some usefull string-manipulation build-in functions, which are [listed here](src/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.ts).
639
+
640
+ ### Expectations
641
+
642
+ `Expect` command describes the desired output of the prompt template (after post-processing)
643
+ It can set limits for the maximum/minimum length of the output, measured in characters, words, sentences, paragraphs,...
644
+
645
+ _Note: LLMs work with tokens, not characters, but in Promptbooks we want to use some human-recognisable and cross-model interoperable units._
646
+
647
+ ```markdown
648
+ # โœจ Sample: Expectations
649
+
650
+ - PROMPTBOOK URL https://promptbook.example.com/samples/postprocessing-2.ptbk.md@v1
651
+ - PROMPTBOOK VERSION 1.0.0
652
+ - INPUTโ€ฏโ€ฏPARAMETER {yourName} Name of the hero
653
+
654
+ ## ๐Ÿ’ฌ Question
655
+
656
+ - EXPECT MAX 30 CHARACTERS
657
+ - EXPECT MIN 2 CHARACTERS
658
+ - EXPECT MAX 3 WORDS
659
+ - EXPECT EXACTLY 1 SENTENCE
660
+ - EXPECT EXACTLY 1 LINE
661
+
662
+ ...
663
+ ```
664
+
665
+ There are two types of expectations which are not strictly symmetrical:
666
+
667
+ #### Minimal expectations
668
+
669
+ - `EXPECT MIN 0 ...` is not valid minimal expectation. It makes no sense.
670
+ - `EXPECT JSON` is both minimal and maximal expectation
671
+ - When you are using `JOKER` in same prompt template, you need to have at least one minimal expectation
672
+
673
+ #### Maximal expectations
674
+
675
+ - `EXPECT MAX 0 ...` is valid maximal expectation. For example, you can expect 0 pages and 2 sentences.
676
+ - `EXPECT JSON` is both minimal and maximal expectation
677
+
678
+ Look 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.
679
+
680
+ <!--
681
+ ### New
682
+ [๐Ÿฅป] Insert here when making new command
683
+ -->
684
+
685
+ ### Execution report
686
+
687
+ Execution report is a simple object or markdown that contains information about the execution of the promptbook.
688
+
689
+ [See the example of such a report](/samples/templates/50-advanced.report.md)
690
+
691
+ <!-- TODO: Write more -->
692
+
693
+ ### Remote server
694
+
695
+ Remote server is a proxy server that uses its execution tools internally and exposes the executor interface externally.
696
+
697
+ You can simply use `RemoteExecutionTools` on client-side javascript and connect to your remote server.
698
+ This is useful to make all logic on browser side but not expose your API keys or no need to use customer's GPU.
699
+
700
+ ## ๐Ÿ‘จโ€๐Ÿ’ป Usage and integration _(for developers)_
701
+
702
+ <!--
703
+
704
+ TODO: [๐Ÿง™โ€โ™‚๏ธ]
705
+
706
+ ### ๐Ÿง™โ€โ™‚๏ธ Using wizzard
707
+
708
+ First you need to install this library:
709
+
710
+ ```bash
711
+ npm install --save @promptbook/wizzard
712
+ ```
713
+
714
+ > TODO: !! Write the Wizzard sample
715
+
716
+ [Usage samples](./samples/usage/)
717
+
718
+ -->
719
+
720
+ ### ๐Ÿ”Œ Usage in Typescript / Javascript
721
+
722
+ - [Simple usage](./samples/usage/simple-script)
723
+ - [Usage with client and remote server](./samples/usage/remote)
724
+
725
+ ## โž•โž– When to use Promptbook?
726
+
727
+ ### โž• When to use
728
+
729
+ - When you are writing app that generates complex things via LLM - like **websites, articles, presentations, code, stories, songs**,...
730
+ - When you want to **separate code from text prompts**
731
+ - When you want to describe **complex prompt pipelines** and don't want to do it in the code
732
+ - When you want to **orchestrate multiple prompts** together
733
+ - When you want to **reuse** parts of prompts in multiple places
734
+ - When you want to **version** your prompts and **test multiple versions**
735
+ - When you want to **log** the execution of prompts and backtrace the issues
736
+
737
+ ### โž– When not to use
738
+
739
+ - When you are writing just a simple chatbot without any extra logic, just system messages
740
+
741
+ ## ๐Ÿœ Known issues
742
+
743
+ <!-- TODO: -->
744
+
745
+ ## ๐Ÿงผ Intentionally not implemented features
746
+
747
+ <!-- TODO: -->
748
+
749
+ ## โ” FAQ
750
+
751
+ If 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).
752
+
753
+ ### Why not just use the OpenAI SDK / Anthropic Claude SDK / ...?
754
+
755
+ Different 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.
756
+
757
+ ### How is it different from the Langchain library?
758
+
759
+ Langchain is primarily aimed at ML developers working in Python. This library is for developers working in javascript/typescript and creating applications for end users.
760
+
761
+ We are considering creating a bridge/converter between these two libraries.
762
+
763
+ <!--
764
+
765
+ ==========
766
+ Include:
767
+ - Langchain is the python library and JavaScript is on second place
768
+ - Langchain primarily focused on making templates, not on combining templates into larger structures
769
+ - at the language level it distinguishes between chat and completion, I need to mix the two into one template pipeline
770
+ - for a non-programmer it's quite hard to work with such a thing and write templates - I would much prefer a system that allows non-technical people to write templates (of which there are many more on the market than free pythonists)
771
+ - The focus of promptbooks is primarily on building user applications, not the data processing, training or autogpt.
772
+ -->
773
+
774
+ ### Promptbooks vs. OpenAI`s GPTs
775
+
776
+ GPTs 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.
777
+
778
+ <!--
779
+ TODO:
780
+ ### Promptbooks vs. Semantic Kernel
781
+
782
+
783
+ -->
784
+
785
+ <!--
786
+ TODO: !
787
+ ### Promptbooks vs. Langtail
788
+
789
+
790
+ -->
791
+
792
+ <!--
793
+ TODO:
794
+ ### Promptbooks vs. Evidentally AI
795
+
796
+ Logging and monitoring
797
+
798
+ -->
799
+
800
+ ### Where should I store my promptbooks?
801
+
802
+ If you use raw SDKs, you just put prompts in the sourcecode, mixed in with typescript, javascript, python or whatever programming language you use.
803
+
804
+ If you use promptbooks, you can store them in several places, each with its own advantages and disadvantages:
805
+
806
+ 1. 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.
807
+
808
+ 2. 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)_.
809
+
810
+ 3. 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.
811
+
812
+ ### What should I do when I need same promptbook in multiple human languages?
813
+
814
+ A single promptbook can be written for several _(human)_ languages at once. However, we recommend that you have separate promptbooks for each language.
815
+
816
+ In large language models, you will get better results if you have prompts in the same language as the user input.
817
+
818
+ The 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.
819
+
820
+ <!--
821
+ TODO: (Maybe)
822
+ ### Why you need to explicitly specify input and output parameters?
823
+ -->
824
+
825
+ <!--
826
+
827
+
828
+
829
+ !
830
+
831
+
832
+
833
+ unit testing
834
+
835
+ escaping
836
+
837
+ how i get block into prompt
838
+
839
+
840
+ ## ๐Ÿšท Limitations
841
+
842
+ function calling
843
+ system message
844
+ iterations
845
+
846
+ -->
847
+
848
+ ## โŒš Changelog
849
+
850
+ See [CHANGELOG.md](./CHANGELOG.md)
851
+
852
+ ## ๐Ÿ“œ License
853
+
854
+ <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>
855
+
856
+ <!--Contributing-->
857
+ <!--โš ๏ธWARNING: This section was generated by https://github.com/hejny/batch-project-editor/blob/main/src/workflows/810-contributing/contributing.ts so every manual change will be overwritten.-->
858
+
859
+ ## ๐Ÿ–‹๏ธ Contributing
860
+
861
+ I 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).
862
+
863
+ You can also โญ star the promptbook package, [follow me on GitHub](https://github.com/hejny) or [various other social networks](https://www.pavolhejny.com/contact/).
864
+
865
+ <!--/Contributing-->