@promptbook/types 0.44.0-8 → 0.44.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.
package/README.md CHANGED
@@ -1,5 +1,751 @@
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/types)](https://socket.dev/npm/package/@promptbook/types)
12
+
13
+ <!--/Badges-->
14
+
15
+ ## 📦 Package `@promptbook/types`
16
+
17
+ - Promptbooks are [divided into several](#-packages) packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook).
18
+ - This package `@promptbook/types` is one part of the promptbook ecosystem.
19
+
20
+ To install this package, run:
21
+
22
+ ```bash
23
+ npm i -D @promptbook/types
24
+ ```
25
+
26
+ This package is usefull when you want to explicitly define types in your code.
27
+
28
+ ```typescript
29
+ import type { PromptbookJson } from '@promptbook/types';
30
+ import { promptbookStringToJson } from '@promptbook/core';
31
+
32
+ const promptbook: PromptbookJson = promptbookStringToJson(...);
33
+ ```
34
+
35
+
36
+ ---
37
+
38
+ Rest of the documentation is common for **entire promptbook ecosystem**:
39
+
40
+ <!--
41
+ TODO: Probbably remove this section only in packages
42
+ > ⚠ Warning: This library is still in early development.
43
+ -->
44
+
45
+ ## 🤍 Whitepaper
46
+
47
+ 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.
48
+
49
+ If you need something more advanced or want to extend the capabilities of LLMs, you generally have three ways to proceed:
50
+
51
+ 1. **Fine-tune** the model to your specifications or even train your own.
52
+ 2. **Prompt-engineer** the prompt to the best shape you can achieve.
53
+ 3. Use **multiple prompts** in a pipeline to get the best result.
54
+
55
+ In any of these situations, but especially in (3), the Promptbook library can make your life easier and make **orchestraror for your prompts**.
56
+
57
+ - **Separation of concerns** between prompt engineer and programmer; between code files and prompt files; and between prompts, templates, templating pipelines, and their execution logic.
58
+ - Set up a **common format** for prompts that is interchangeable between projects and language/technology stacks.
59
+ - **Preprocessing** and cleaning the input data from the user.
60
+ - Use default values - **Jokers** to bypass some parts of the pipeline.
61
+ - **Expect** some specific output from the model.
62
+ - **Retry** mismatched outputs.
63
+ - **Combine** multiple models together.
64
+ - Interactive **User interaction** with the model and the user.
65
+ - Leverage **external** sources (like ChatGPT plugins or OpenAI's GPTs).
66
+ - Simplify your code to be **DRY** and not repeat all the boilerplate code for each prompt.
67
+ - **Versioning** of promptbooks
68
+ - **Reuse** parts of promptbooks in/between projects.
69
+ - Run the LLM **optimally** in parallel, with the best _cost/quality_ ratio or _speed/quality_ ratio.
70
+ - **Execution report** to see what happened during the execution.
71
+ - **Logging** the results of the promptbooks.
72
+ - _(Not ready yet)_ **Caching** calls to LLMs to save money and time.
73
+ - _(Not ready yet)_ Extend one prompt book from another one.
74
+ - _(Not ready yet)_ Leverage the **streaming** to make super cool UI/UX.
75
+ - _(Not ready yet)_ **A/B testing** to determine which prompt works best for the job.
76
+
77
+ ![WebGPT](./other/screencasts/screencast-fiabciakcmgepblmdkmemdbbkilneeeh-2023.10.26-21_46_17.gif)
78
+
79
+ ## 🧔 Promptbook _(for prompt-engeneers)_
80
+
81
+ **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.
82
+
83
+ - Multiple promptbooks forms a library which will become a **part of your application codebase**.
84
+ - Theese promptbooks are designed such as they **can be written by non-programmers**.
85
+
86
+ <!-- TODO: [🧠] Make some more clear escaping -->
87
+
88
+ ### Sample:
89
+
90
+ File `write-website-content.ptbk.md`:
91
+
92
+ <!------------------------[ Sample: ]------------------------>
93
+
94
+ > # 🌍 Create website content
95
+ >
96
+ > Instructions for creating web page content.
97
+ >
98
+ > - PROMPTBOOK URL https://promptbook.webgpt.com/en/write-website-content.ptbk.md@v0.1.0
99
+ > - PROMPTBOOK VERSION 0.0.1
100
+ > - INPUT  PARAM `{rawTitle}` Automatically suggested a site name or empty text
101
+ > - INPUT  PARAM `{rawAssigment}` Automatically generated site entry from image recognition
102
+ > - OUTPUT PARAM `{content}` Web content
103
+ > - OUTPUT PARAM `{keywords}` Keywords
104
+ >
105
+ > ## 👤 Specifying the assigment
106
+ >
107
+ > What is your web about?
108
+ >
109
+ > - PROMPT DIALOG
110
+ >
111
+ > ```
112
+ > {rawAssigment}
113
+ > ```
114
+ >
115
+ > `-> {assigment}` Website assignment and specification
116
+ >
117
+ > ## ✨ Improving the title
118
+ >
119
+ > - MODEL VARIANT Chat
120
+ > - MODEL NAME `gpt-4`
121
+ > - POSTPROCESSING `unwrapResult`
122
+ >
123
+ > ```
124
+ > As an experienced marketing specialist, you have been entrusted with improving the name of your client's business.
125
+ >
126
+ > A suggested name from a client:
127
+ > "{rawTitle}"
128
+ >
129
+ > Assignment from customer:
130
+ >
131
+ > > {assigment}
132
+ >
133
+ > ## Instructions:
134
+ >
135
+ > - Write only one name suggestion
136
+ > - The name will be used on the website, business cards, visuals, etc.
137
+ > ```
138
+ >
139
+ > `-> {enhancedTitle}` Enhanced title
140
+ >
141
+ > ## 👤 Website title approval
142
+ >
143
+ > Is the title for your website okay?
144
+ >
145
+ > - PROMPT DIALOG
146
+ >
147
+ > ```
148
+ > {enhancedTitle}
149
+ > ```
150
+ >
151
+ > `-> {title}` Title for the website
152
+ >
153
+ > ## 🐰 Cunning subtitle
154
+ >
155
+ > - MODEL VARIANT Chat
156
+ > - MODEL NAME `gpt-4`
157
+ > - POSTPROCESSING `unwrapResult`
158
+ >
159
+ > ```
160
+ > As an experienced copywriter, you have been entrusted with creating a claim for the "{title}" web page.
161
+ >
162
+ > A website assignment from a customer:
163
+ >
164
+ > > {assigment}
165
+ >
166
+ > ## Instructions:
167
+ >
168
+ > - Write only one name suggestion
169
+ > - Claim will be used on website, business cards, visuals, etc.
170
+ > - Claim should be punchy, funny, original
171
+ > ```
172
+ >
173
+ > `-> {claim}` Claim for the web
174
+ >
175
+ > ## 🚦 Keyword analysis
176
+ >
177
+ > - MODEL VARIANT Chat
178
+ > - MODEL NAME `gpt-4`
179
+ >
180
+ > ```
181
+ > As an experienced SEO specialist, you have been entrusted with creating keywords for the website "{title}".
182
+ >
183
+ > Website assignment from the customer:
184
+ >
185
+ > > {assigment}
186
+ >
187
+ > ## Instructions:
188
+ >
189
+ > - Write a list of keywords
190
+ > - Keywords are in basic form
191
+ >
192
+ > ## Example:
193
+ >
194
+ > - Ice cream
195
+ > - Olomouc
196
+ > - Quality
197
+ > - Family
198
+ > - Tradition
199
+ > - Italy
200
+ > - Craft
201
+ >
202
+ > ```
203
+ >
204
+ > `-> {keywords}` Keywords
205
+ >
206
+ > ## 🔗 Combine the beginning
207
+ >
208
+ > - SIMPLE TEMPLATE
209
+ >
210
+ > ```
211
+ >
212
+ > # {title}
213
+ >
214
+ > > {claim}
215
+ >
216
+ > ```
217
+ >
218
+ > `-> {contentBeginning}` Beginning of web content
219
+ >
220
+ > ## 🖋 Write the content
221
+ >
222
+ > - MODEL VARIANT Completion
223
+ > - MODEL NAME `gpt-3.5-turbo-instruct`
224
+ >
225
+ > ```
226
+ > As an experienced copywriter and web designer, you have been entrusted with creating text for a new website {title}.
227
+ >
228
+ > A website assignment from a customer:
229
+ >
230
+ > > {assigment}
231
+ >
232
+ > ## Instructions:
233
+ >
234
+ > - Text formatting is in Markdown
235
+ > - Be concise and to the point
236
+ > - Use keywords, but they should be naturally in the text
237
+ > - This is the complete content of the page, so don't forget all the important information and elements the page should contain
238
+ > - Use headings, bullets, text formatting
239
+ >
240
+ > ## Keywords:
241
+ >
242
+ > {keywords}
243
+ >
244
+ > ## Web Content:
245
+ >
246
+ > {contentBeginning}
247
+ > ```
248
+ >
249
+ > `-> {contentBody}` Middle of the web content
250
+ >
251
+ > ## 🔗 Combine the content
252
+ >
253
+ > - SIMPLE TEMPLATE
254
+ >
255
+ > ```markdown
256
+ > {contentBeginning}
257
+ >
258
+ > {contentBody}
259
+ > ```
260
+ >
261
+ > `-> {content}`
262
+
263
+ <!------------------------[ /Sample ]------------------------>
264
+
265
+ Following is the scheme how the promptbook above is executed:
266
+
267
+ ```mermaid
268
+ %% 🔮 Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually
269
+
270
+ flowchart LR
271
+ subgraph "🌍 Create website content"
272
+
273
+ direction TB
274
+
275
+ input((Input)):::input
276
+ templateSpecifyingTheAssigment(👤 Specifying the assigment)
277
+ input--"{rawAssigment}"-->templateSpecifyingTheAssigment
278
+ templateImprovingTheTitle(✨ Improving the title)
279
+ input--"{rawTitle}"-->templateImprovingTheTitle
280
+ templateSpecifyingTheAssigment--"{assigment}"-->templateImprovingTheTitle
281
+ templateWebsiteTitleApproval(👤 Website title approval)
282
+ templateImprovingTheTitle--"{enhancedTitle}"-->templateWebsiteTitleApproval
283
+ templateCunningSubtitle(🐰 Cunning subtitle)
284
+ templateWebsiteTitleApproval--"{title}"-->templateCunningSubtitle
285
+ templateSpecifyingTheAssigment--"{assigment}"-->templateCunningSubtitle
286
+ templateKeywordAnalysis(🚦 Keyword analysis)
287
+ templateWebsiteTitleApproval--"{title}"-->templateKeywordAnalysis
288
+ templateSpecifyingTheAssigment--"{assigment}"-->templateKeywordAnalysis
289
+ templateCombineTheBeginning(🔗 Combine the beginning)
290
+ templateWebsiteTitleApproval--"{title}"-->templateCombineTheBeginning
291
+ templateCunningSubtitle--"{claim}"-->templateCombineTheBeginning
292
+ templateWriteTheContent(🖋 Write the content)
293
+ templateWebsiteTitleApproval--"{title}"-->templateWriteTheContent
294
+ templateSpecifyingTheAssigment--"{assigment}"-->templateWriteTheContent
295
+ templateKeywordAnalysis--"{keywords}"-->templateWriteTheContent
296
+ templateCombineTheBeginning--"{contentBeginning}"-->templateWriteTheContent
297
+ templateCombineTheContent(🔗 Combine the content)
298
+ templateCombineTheBeginning--"{contentBeginning}"-->templateCombineTheContent
299
+ templateWriteTheContent--"{contentBody}"-->templateCombineTheContent
300
+
301
+ templateCombineTheContent--"{content}"-->output
302
+ output((Output)):::output
303
+
304
+ classDef input color: grey;
305
+ classDef output color: grey;
306
+
307
+ end;
308
+ ```
309
+
310
+ [More template samples](./samples/templates/)
311
+
312
+ _Note: We are using [postprocessing functions](#postprocessing-functions) like `unwrapResult` that can be used to postprocess the result._
313
+
314
+ ## 📦 Packages
315
+
316
+ This library is divided into several packages, all are published from [single monorepo](https://github.com/webgptorg/promptbook):
317
+
318
+ <!--[🔠]-->
319
+
320
+ - **[@promptbook/core](https://www.npmjs.com/package/@promptbook/core)** - Core of the library, it contains the main logic for promptbooks
321
+ - **[@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
322
+ - _(Not finished)_ **[@promptbook/wizzard](https://www.npmjs.com/package/@promptbook/wizzard)** - Wizard for creating+running promptbooks in single line
323
+ - **[@promptbook/execute-javascript](https://www.npmjs.com/package/@promptbook/execute-javascript)** - Execution tools for javascript inside promptbooks
324
+ - **[@promptbook/openai](https://www.npmjs.com/package/@promptbook/openai)** - Execution tools for OpenAI API, wrapper around OpenAI SDK
325
+ - **[@promptbook/remote-client](https://www.npmjs.com/package/@promptbook/remote-client)** - Remote client for remote execution of promptbooks
326
+ - **[@promptbook/remote-server](https://www.npmjs.com/package/@promptbook/remote-server)** - Remote server for remote execution of promptbooks
327
+ - **[@promptbook/types](https://www.npmjs.com/package/@promptbook/types)** - Just typescript types used in the library
328
+ - **[@promptbook/cli](https://www.npmjs.com/package/@promptbook/cli)** - Command line interface utilities for promptbooks
329
+
330
+ ## 📚 Dictionary
331
+
332
+ The following glossary is used to clarify certain basic concepts:
333
+
334
+ ### Prompt
335
+
336
+ Prompt in a text along with model requirements, but without any execution or templating logic.
337
+
338
+ For example:
339
+
340
+ ```json
341
+ {
342
+ "request": "Which sound does a cat make?",
343
+ "modelRequirements": {
344
+ "variant": "CHAT"
345
+ }
346
+ }
347
+ ```
348
+
349
+ ```json
350
+ {
351
+ "request": "I am a cat.\nI like to eat fish.\nI like to sleep.\nI like to play with a ball.\nI l",
352
+ "modelRequirements": {
353
+ "variant": "COMPLETION"
354
+ }
355
+ }
356
+ ```
357
+
358
+ ### Prompt Template
359
+
360
+ Similar concept to Prompt, but with templating logic.
361
+
362
+ For example:
363
+
364
+ ```json
365
+ {
366
+ "request": "Which sound does a {animalName} make?",
367
+ "modelRequirements": {
368
+ "variant": "CHAT"
369
+ }
370
+ }
371
+ ```
372
+
373
+ ### Model Requirements
374
+
375
+ Abstract way to specify the LLM.
376
+ It does not specify the LLM with concrete version itself, only the requirements for the LLM.
377
+ _NOT chatgpt-3.5-turbo BUT CHAT variant of GPT-3.5._
378
+
379
+ For example:
380
+
381
+ ```json
382
+ {
383
+ "variant": "CHAT",
384
+ "version": "GPT-3.5",
385
+ "temperature": 0.7
386
+ }
387
+ ```
388
+
389
+ ### Execution type
390
+
391
+ Each block of promptbook can have a different execution type.
392
+ It is specified in list of requirements for the block.
393
+ By default, it is `Prompt template`
394
+
395
+ - _(default)_ `Prompt template` The block is a prompt template and is executed by LLM (OpenAI, Azure,...)
396
+ - `SIMPLE TEMPLATE` The block is a simple text template which is just filled with parameters
397
+ - `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.
398
+ - `PROMPT DIALOG` Ask user for input
399
+
400
+ ### Parameters
401
+
402
+ Parameters that are placed in the prompt template and replaced to create the prompt.
403
+ It is a simple key-value object.
404
+
405
+ ```json
406
+ {
407
+ "animalName": "cat",
408
+ "animalSound": "Meow!"
409
+ }
410
+ ```
411
+
412
+ There are three types of template parameters, depending on how they are used in the promptbook:
413
+
414
+ - **INPUT PARAMETER**s are required to execute the promptbook.
415
+ - **Intermediate parameters** are used internally in the promptbook.
416
+ - **OUTPUT PARAMETER**s are explicitelly marked and they are returned as the result of the promptbook execution.
417
+
418
+ _Note: Parameter can be both intermedite and output at the same time._
419
+
420
+ ### Promptbook
421
+
422
+ Promptbook is **core concept of this library**.
423
+ It represents a series of prompt templates chained together to form a **pipeline** / one big prompt template with input and result parameters.
424
+
425
+ Internally it can have multiple formats:
426
+
427
+ - **.ptbk.md file** in custom markdown format described above
428
+ - _(concept)_ **.ptbk** format, custom fileextension based on markdown
429
+ - _(internal)_ **JSON** format, parsed from the .ptbk.md file
430
+
431
+ ### Promptbook **Library**
432
+
433
+ Library of all promptbooks used in your application.
434
+ 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.
435
+
436
+ ### Prompt Result
437
+
438
+ Prompt result is the simplest concept of execution.
439
+ It is the result of executing one prompt _(NOT a template)_.
440
+
441
+ For example:
442
+
443
+ ```json
444
+ {
445
+ "response": "Meow!",
446
+ "model": "chatgpt-3.5-turbo"
447
+ }
448
+ ```
449
+
450
+ ### Execution Tools
451
+
452
+ `ExecutionTools` is an interface which contains all the tools needed to execute prompts.
453
+ It contais 3 subtools:
454
+
455
+ - `NaturalExecutionTools`
456
+ - `ScriptExecutionTools`
457
+ - `UserInterfaceTools`
458
+
459
+ Which are described below:
460
+
461
+ #### Natural Execution Tools
462
+
463
+ `NaturalExecutionTools` is a container for all the tools needed to execute prompts to large language models like GPT-4.
464
+ On its interface it exposes common methods for prompt execution.
465
+ Internally it calls OpenAI, Azure, GPU, proxy, cache, logging,...
466
+
467
+ `NaturalExecutionTools` an abstract interface that is implemented by concrete execution tools:
468
+
469
+ - `OpenAiExecutionTools`
470
+ - _(Not implemented yet)_ `AnthropicClaudeExecutionTools`
471
+ - _(Not implemented yet)_ `AzureOpenAiExecutionTools`
472
+ - _(Not implemented yet)_ `BardExecutionTools`
473
+ - _(Not implemented yet)_ `LamaExecutionTools`
474
+ - _(Not implemented yet)_ `GpuExecutionTools`
475
+ - And a special case are `RemoteNaturalExecutionTools` that connect to a remote server and run one of the above execution tools on that server.
476
+ - The second special case is `MockedEchoNaturalExecutionTools` that is used for testing and mocking.
477
+ - 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.
478
+
479
+ #### Script Execution Tools
480
+
481
+ `ScriptExecutionTools` is an abstract container that represents all the tools needed to EXECUTE SCRIPTs. It is implemented by concrete execution tools:
482
+
483
+ - `JavascriptExecutionTools` is a wrapper around `vm2` module that executes javascript code in a sandbox.
484
+ - `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.
485
+ - _(Not implemented yet)_ `TypescriptExecutionTools` executes typescript code in a sandbox.
486
+ - _(Not implemented yet)_ `PythonExecutionTools` executes python code in a sandbox.
487
+
488
+ There are [postprocessing functions](#postprocessing-functions) that can be used to postprocess the result.
489
+
490
+ #### User Interface Tools
491
+
492
+ `UserInterfaceTools` is an abstract container that represents all the tools needed to interact with the user. It is implemented by concrete execution tools:
493
+
494
+ - _(Not implemented yet)_ `ConsoleInterfaceTools` is a wrapper around `readline` module that interacts with the user via console.
495
+ - `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.
496
+ - `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 -->
497
+
498
+ ### Executor
499
+
500
+ Executor is a simple async function that takes **input parameters** and returns **output parameters**.
501
+ It is constructed by combining execution tools and promptbook to execute together.
502
+
503
+ ### 🃏 Jokers
504
+
505
+ Joker is a previously defined parameter that is used to bypass some parts of the pipeline.
506
+ 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.
507
+
508
+ If none of the jokers meet the requirements, the prompt template is executed as usual.
509
+
510
+ 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.
511
+
512
+ 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.
513
+
514
+ Look at [jokers.ptbk.md](samples/templates/41-jokers.ptbk.md) sample.
515
+
516
+ ### Postprocessing functions
517
+
518
+ You can define postprocessing functions when creating `JavascriptEvalExecutionTools`:
519
+
520
+ ```
521
+
522
+ ```
523
+
524
+ Additionally there are some usefull string-manipulation build-in functions, which are [listed here](src/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.ts).
525
+
526
+ ### Expectations
527
+
528
+ `Expect` command describes the desired output of the prompt template (after post-processing)
529
+ It can set limits for the maximum/minimum length of the output, measured in characters, words, sentences, paragraphs,...
530
+
531
+ _Note: LLMs work with tokens, not characters, but in Promptbooks we want to use some human-recognisable and cross-model interoperable units._
532
+
533
+ ```markdown
534
+ # ✨ Sample: Expectations
535
+
536
+ - PROMPTBOOK URL https://promptbook.example.com/samples/postprocessing-2.ptbk.md@v1
537
+ - PROMPTBOOK VERSION 1.0.0
538
+ - INPUT  PARAMETER {yourName} Name of the hero
539
+
540
+ ## 💬 Question
541
+
542
+ - EXPECT MAX 30 CHARACTERS
543
+ - EXPECT MIN 2 CHARACTERS
544
+ - EXPECT MAX 3 WORDS
545
+ - EXPECT EXACTLY 1 SENTENCE
546
+ - EXPECT EXACTLY 1 LINE
547
+
548
+ ...
549
+ ```
550
+
551
+ There are two types of expectations which are not strictly symmetrical:
552
+
553
+ #### Minimal expectations
554
+
555
+ - `EXPECT MIN 0 ...` is not valid minimal expectation. It makes no sense.
556
+ - `EXPECT JSON` is both minimal and maximal expectation
557
+ - When you are using `JOKER` in same prompt template, you need to have at least one minimal expectation
558
+
559
+ #### Maximal expectations
560
+
561
+ - `EXPECT MAX 0 ...` is valid maximal expectation. For example, you can expect 0 pages and 2 sentences.
562
+ - `EXPECT JSON` is both minimal and maximal expectation
563
+
564
+ 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.
565
+
566
+ <!--
567
+ ### New
568
+ [🥻] Insert here when making new command
569
+ -->
570
+
571
+ ### Execution report
572
+
573
+ Execution report is a simple object or markdown that contains information about the execution of the promptbook.
574
+
575
+ [See the example of such a report](/samples/templates/50-advanced.report.md)
576
+
577
+ <!-- TODO: Write more -->
578
+
579
+ ### Remote server
580
+
581
+ Remote server is a proxy server that uses its execution tools internally and exposes the executor interface externally.
582
+
583
+ You can simply use `RemoteExecutionTools` on client-side javascript and connect to your remote server.
584
+ This is useful to make all logic on browser side but not expose your API keys or no need to use customer's GPU.
585
+
586
+ ## 👨‍💻 Usage and integration _(for developers)_
587
+
588
+ <!--
589
+
590
+ TODO: [🧙‍♂️]
591
+
592
+ ### 🧙‍♂️ Using wizzard
593
+
594
+ First you need to install this library:
595
+
596
+ ```bash
597
+ npm install --save @promptbook/wizzard
598
+ ```
599
+
600
+ > TODO: !! Write the Wizzard sample
601
+
602
+ [Usage samples](./samples/usage/)
603
+
604
+ -->
605
+
606
+ ### 🔌 Usage in Typescript / Javascript
607
+
608
+ - [Simple usage](./samples/usage/simple-script)
609
+ - [Usage with client and remote server](./samples/usage/remote)
610
+
611
+ ## ➕➖ When to use Promptbook?
612
+
613
+ ### ➕ When to use
614
+
615
+ - When you are writing app that generates complex things via LLM - like **websites, articles, presentations, code, stories, songs**,...
616
+ - When you want to **separate code from text prompts**
617
+ - When you want to describe **complex prompt pipelines** and don't want to do it in the code
618
+ - When you want to **orchestrate multiple prompts** together
619
+ - When you want to **reuse** parts of prompts in multiple places
620
+ - When you want to **version** your prompts and **test multiple versions**
621
+ - When you want to **log** the execution of prompts and backtrace the issues
622
+
623
+ ### ➖ When not to use
624
+
625
+ - When you are writing just a simple chatbot without any extra logic, just system messages
626
+
627
+ ## 🐜 Known issues
628
+
629
+ <!-- TODO: -->
630
+
631
+ ## 🧼 Intentionally not implemented features
632
+
633
+ <!-- TODO: -->
634
+
635
+ ## ❔ FAQ
636
+
637
+ 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).
638
+
639
+ ### Why not just use the OpenAI SDK / Anthropic Claude SDK / ...?
640
+
641
+ 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.
642
+
643
+ ### How is it different from the Langchain library?
644
+
645
+ 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.
646
+
647
+ We are considering creating a bridge/converter between these two libraries.
648
+
649
+ <!--
650
+
651
+ ==========
652
+ Include:
653
+ - Langchain is the python library and JavaScript is on second place
654
+ - Langchain primarily focused on making templates, not on combining templates into larger structures
655
+ - at the language level it distinguishes between chat and completion, I need to mix the two into one template pipeline
656
+ - 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)
657
+ - The focus of promptbooks is primarily on building user applications, not the data processing, training or autogpt.
658
+ -->
659
+
660
+ ### Promptbooks vs. OpenAI`s GPTs
661
+
662
+ 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.
663
+
664
+ <!--
665
+ TODO:
666
+ ### Promptbooks vs. Semantic Kernel
667
+
668
+
669
+ -->
670
+
671
+ <!--
672
+ TODO: !
673
+ ### Promptbooks vs. Langtail
674
+
675
+
676
+ -->
677
+
678
+ <!--
679
+ TODO:
680
+ ### Promptbooks vs. Evidentally AI
681
+
682
+ Logging and monitoring
683
+
684
+ -->
685
+
686
+ ### Where should I store my promptbooks?
687
+
688
+ If you use raw SDKs, you just put prompts in the sourcecode, mixed in with typescript, javascript, python or whatever programming language you use.
689
+
690
+ If you use promptbooks, you can store them in several places, each with its own advantages and disadvantages:
691
+
692
+ 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.
693
+
694
+ 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)_.
695
+
696
+ 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.
697
+
698
+ ### What should I do when I need same promptbook in multiple human languages?
699
+
700
+ A single promptbook can be written for several _(human)_ languages at once. However, we recommend that you have separate promptbooks for each language.
701
+
702
+ In large language models, you will get better results if you have prompts in the same language as the user input.
703
+
704
+ 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.
705
+
706
+ <!--
707
+ TODO: (Maybe)
708
+ ### Why you need to explicitly specify input and output parameters?
709
+ -->
710
+
711
+ <!--
712
+
713
+
714
+
715
+ !
716
+
717
+
718
+
719
+ unit testing
720
+
721
+ escaping
722
+
723
+ how i get block into prompt
724
+
725
+
726
+ ## 🚷 Limitations
727
+
728
+ function calling
729
+ system message
730
+ iterations
731
+
732
+ -->
733
+
734
+ ## ⌚ Changelog
735
+
736
+ See [CHANGELOG.md](./CHANGELOG.md)
737
+
738
+ ## 📜 License
739
+
740
+ <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>
741
+
742
+ <!--Contributing-->
743
+ <!--⚠️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.-->
744
+
745
+ ## 🖋️ Contributing
746
+
747
+ 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).
748
+
749
+ 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/).
750
+
751
+ <!--/Contributing-->
@@ -1,3 +1,4 @@
1
+ import { spaceTrim } from 'spacetrim';
1
2
  import { prettifyPromptbookString } from '../conversion/prettify/prettifyPromptbookString';
2
3
  import { parseNumber } from '../conversion/utils/parseNumber';
3
4
  import { assertsExecutionSuccessful } from '../execution/assertsExecutionSuccessful';
@@ -44,17 +45,18 @@ import { unwrapResult } from '../utils/unwrapResult';
44
45
  export { assertsExecutionSuccessful, checkExpectations, executionReportJsonToString, ExecutionReportStringOptions, ExecutionReportStringOptionsDefaults, extractAllBlocksFromMarkdown, // <- [🌻]
45
46
  extractAllListItemsFromMarkdown, extractBlock, // <- [🌻]
46
47
  extractOneBlockFromMarkdown, isPassingExpectations, isValidJsonString, parseNumber, // <- [🌻]
47
- prettifyPromptbookString, removeContentComments, removeEmojis, removeMarkdownFormatting, removeQuotes, replaceParameters, trimCodeBlock, trimEndOfCodeBlock, unwrapResult, };
48
+ prettifyPromptbookString, removeContentComments, removeEmojis, removeMarkdownFormatting, removeQuotes, replaceParameters, spaceTrim, trimCodeBlock, trimEndOfCodeBlock, unwrapResult, };
48
49
  export { countCharacters, countLines, countPages, countParagraphs, countSentences, CountUtils, countWords };
49
50
  export { splitIntoSentences };
50
51
  export declare const normalizeTo: {
51
52
  camelCase: typeof normalizeTo_camelCase;
52
53
  PascalCase: typeof normalizeTo_PascalCase;
53
- 'SCREAMING-CASE': typeof normalizeTo_SCREAMING_CASE;
54
+ SCREAMING_CASE: typeof normalizeTo_SCREAMING_CASE;
54
55
  snake_case: typeof normalizeTo_snake_case;
55
56
  'kebab-case': typeof normalizeToKebabCase;
56
57
  };
57
58
  export { capitalize, decapitalize, DIACRITIC_VARIANTS_LETTERS, IKeywords, isValidKeyword, nameToUriPart, nameToUriParts, normalizeTo_camelCase, normalizeTo_PascalCase, normalizeTo_SCREAMING_CASE, normalizeTo_snake_case, normalizeToKebabCase, normalizeWhitespaces, parseKeywords, parseKeywordsFromString, removeDiacritics, searchKeywords, string_keyword, };
58
59
  /**
59
60
  * TODO: [🧠] Maybe create some indipendent package like `markdown-tools` from both here exported and @private utilities
61
+ * Note: [🕙] It does not make sence to have simple lower / UPPER case normalization
60
62
  */
@@ -1,11 +1,15 @@
1
1
  import type { Expectations } from '../../../../types/PromptbookJson/PromptTemplateJson';
2
+ import { PostprocessingFunction } from '../../script-execution-tools/javascript/JavascriptExecutionToolsOptions';
2
3
  /**
3
4
  * Gets the expectations and creates a fake text that meets the expectations
4
5
  *
6
+ * Note: You can provide postprocessing functions to modify the text before checking the expectations
7
+ * The result will be the text BEFORE the postprocessing
8
+ *
5
9
  * @private internal util for MockedFackedNaturalExecutionTools
6
10
  */
7
- export declare function $fakeTextToExpectations(expectations: Expectations): string;
11
+ export declare function $fakeTextToExpectations(expectations: Expectations, postprocessing?: Array<PostprocessingFunction>): Promise<string>;
8
12
  /**
9
- * TODO: Implement better
13
+ * TODO: Implement better - create FakeLLM from this
10
14
  * TODO: [💝] Unite object for expecting amount and format - use here also a format
11
15
  */
@@ -15,8 +15,12 @@ export type JavascriptExecutionToolsOptions = CommonExecutionToolsOptions & {
15
15
  * Note: There are also some built-in functions available:
16
16
  * @see ./JavascriptEvalExecutionTools.ts
17
17
  */
18
- functions?: Record<string_javascript_name, ((value: string) => Promisable<string>) | Function>;
18
+ functions?: Record<string_javascript_name, PostprocessingFunction>;
19
19
  };
20
+ /**
21
+ * Function that can be used to postprocess the output of the LLM
22
+ */
23
+ export type PostprocessingFunction = ((value: string) => Promisable<string>) | Function;
20
24
  /**
21
25
  * TODO: [🧠][💙] Distinct between options passed into ExecutionTools and to ExecutionTools.execute
22
26
  */
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Converts anything to string that can be used for debugging and logging
3
+ *
4
+ * @param value String value for logging
5
+ * @private Internal util
6
+ */
7
+ export declare function unknownToString(value: unknown): string;
@@ -1,4 +1,5 @@
1
1
  import type { string_name, string_prompt, string_promptbook_url_with_hashtemplate, string_title } from '.././types/typeAliases';
2
+ import { PostprocessingFunction } from '../execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions';
2
3
  import type { ModelRequirements } from './ModelRequirements';
3
4
  import type { Expectations } from './PromptbookJson/PromptTemplateJson';
4
5
  /**
@@ -24,6 +25,10 @@ export type Prompt = {
24
25
  * Requirements for the model
25
26
  */
26
27
  readonly modelRequirements: ModelRequirements;
28
+ /**
29
+ * List of postprocessing steps that are executed after the prompt
30
+ */
31
+ readonly postprocessing?: Array<PostprocessingFunction>;
27
32
  /**
28
33
  * Expectations for the answer
29
34
  *
@@ -121,6 +121,7 @@ interface PromptTemplateJsonCommon {
121
121
  * Expect this format of the answer
122
122
  *
123
123
  * Note: Expectations are performed after all postprocessing steps
124
+ * @deprecated [💝]
124
125
  */
125
126
  readonly expectFormat?: ExpectFormatCommand['format'];
126
127
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/types",
3
- "version": "0.44.0-8",
3
+ "version": "0.44.0",
4
4
  "description": "Library to supercharge your use of large language models",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -28,14 +28,14 @@
28
28
  "text-generation",
29
29
  "language-model"
30
30
  ],
31
- "license": "SEE LICENSE IN LICENSE",
31
+ "license": "CC-BY-4.0",
32
32
  "bugs": {
33
33
  "url": "https://github.com/webgptorg/promptbook/issues"
34
34
  },
35
35
  "homepage": "https://www.npmjs.com/package/@promptbook/core",
36
36
  "dependencies": {},
37
37
  "peerDependencies": {
38
- "@promptbook/core": "0.44.0-8"
38
+ "@promptbook/core": "0.44.0"
39
39
  },
40
40
  "main": "./umd/index.umd.js",
41
41
  "module": "./esm/index.es.js",
@@ -1,3 +1,4 @@
1
+ import { spaceTrim } from 'spacetrim';
1
2
  import { prettifyPromptbookString } from '../conversion/prettify/prettifyPromptbookString';
2
3
  import { parseNumber } from '../conversion/utils/parseNumber';
3
4
  import { assertsExecutionSuccessful } from '../execution/assertsExecutionSuccessful';
@@ -44,17 +45,18 @@ import { unwrapResult } from '../utils/unwrapResult';
44
45
  export { assertsExecutionSuccessful, checkExpectations, executionReportJsonToString, ExecutionReportStringOptions, ExecutionReportStringOptionsDefaults, extractAllBlocksFromMarkdown, // <- [🌻]
45
46
  extractAllListItemsFromMarkdown, extractBlock, // <- [🌻]
46
47
  extractOneBlockFromMarkdown, isPassingExpectations, isValidJsonString, parseNumber, // <- [🌻]
47
- prettifyPromptbookString, removeContentComments, removeEmojis, removeMarkdownFormatting, removeQuotes, replaceParameters, trimCodeBlock, trimEndOfCodeBlock, unwrapResult, };
48
+ prettifyPromptbookString, removeContentComments, removeEmojis, removeMarkdownFormatting, removeQuotes, replaceParameters, spaceTrim, trimCodeBlock, trimEndOfCodeBlock, unwrapResult, };
48
49
  export { countCharacters, countLines, countPages, countParagraphs, countSentences, CountUtils, countWords };
49
50
  export { splitIntoSentences };
50
51
  export declare const normalizeTo: {
51
52
  camelCase: typeof normalizeTo_camelCase;
52
53
  PascalCase: typeof normalizeTo_PascalCase;
53
- 'SCREAMING-CASE': typeof normalizeTo_SCREAMING_CASE;
54
+ SCREAMING_CASE: typeof normalizeTo_SCREAMING_CASE;
54
55
  snake_case: typeof normalizeTo_snake_case;
55
56
  'kebab-case': typeof normalizeToKebabCase;
56
57
  };
57
58
  export { capitalize, decapitalize, DIACRITIC_VARIANTS_LETTERS, IKeywords, isValidKeyword, nameToUriPart, nameToUriParts, normalizeTo_camelCase, normalizeTo_PascalCase, normalizeTo_SCREAMING_CASE, normalizeTo_snake_case, normalizeToKebabCase, normalizeWhitespaces, parseKeywords, parseKeywordsFromString, removeDiacritics, searchKeywords, string_keyword, };
58
59
  /**
59
60
  * TODO: [🧠] Maybe create some indipendent package like `markdown-tools` from both here exported and @private utilities
61
+ * Note: [🕙] It does not make sence to have simple lower / UPPER case normalization
60
62
  */
@@ -1,11 +1,15 @@
1
1
  import type { Expectations } from '../../../../types/PromptbookJson/PromptTemplateJson';
2
+ import { PostprocessingFunction } from '../../script-execution-tools/javascript/JavascriptExecutionToolsOptions';
2
3
  /**
3
4
  * Gets the expectations and creates a fake text that meets the expectations
4
5
  *
6
+ * Note: You can provide postprocessing functions to modify the text before checking the expectations
7
+ * The result will be the text BEFORE the postprocessing
8
+ *
5
9
  * @private internal util for MockedFackedNaturalExecutionTools
6
10
  */
7
- export declare function $fakeTextToExpectations(expectations: Expectations): string;
11
+ export declare function $fakeTextToExpectations(expectations: Expectations, postprocessing?: Array<PostprocessingFunction>): Promise<string>;
8
12
  /**
9
- * TODO: Implement better
13
+ * TODO: Implement better - create FakeLLM from this
10
14
  * TODO: [💝] Unite object for expecting amount and format - use here also a format
11
15
  */
@@ -15,8 +15,12 @@ export type JavascriptExecutionToolsOptions = CommonExecutionToolsOptions & {
15
15
  * Note: There are also some built-in functions available:
16
16
  * @see ./JavascriptEvalExecutionTools.ts
17
17
  */
18
- functions?: Record<string_javascript_name, ((value: string) => Promisable<string>) | Function>;
18
+ functions?: Record<string_javascript_name, PostprocessingFunction>;
19
19
  };
20
+ /**
21
+ * Function that can be used to postprocess the output of the LLM
22
+ */
23
+ export type PostprocessingFunction = ((value: string) => Promisable<string>) | Function;
20
24
  /**
21
25
  * TODO: [🧠][💙] Distinct between options passed into ExecutionTools and to ExecutionTools.execute
22
26
  */
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Converts anything to string that can be used for debugging and logging
3
+ *
4
+ * @param value String value for logging
5
+ * @private Internal util
6
+ */
7
+ export declare function unknownToString(value: unknown): string;
@@ -1,4 +1,5 @@
1
1
  import type { string_name, string_prompt, string_promptbook_url_with_hashtemplate, string_title } from '.././types/typeAliases';
2
+ import { PostprocessingFunction } from '../execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions';
2
3
  import type { ModelRequirements } from './ModelRequirements';
3
4
  import type { Expectations } from './PromptbookJson/PromptTemplateJson';
4
5
  /**
@@ -24,6 +25,10 @@ export type Prompt = {
24
25
  * Requirements for the model
25
26
  */
26
27
  readonly modelRequirements: ModelRequirements;
28
+ /**
29
+ * List of postprocessing steps that are executed after the prompt
30
+ */
31
+ readonly postprocessing?: Array<PostprocessingFunction>;
27
32
  /**
28
33
  * Expectations for the answer
29
34
  *
@@ -121,6 +121,7 @@ interface PromptTemplateJsonCommon {
121
121
  * Expect this format of the answer
122
122
  *
123
123
  * Note: Expectations are performed after all postprocessing steps
124
+ * @deprecated [💝]
124
125
  */
125
126
  readonly expectFormat?: ExpectFormatCommand['format'];
126
127
  /**