modprompt 0.0.1

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 ADDED
@@ -0,0 +1,201 @@
1
+ # Modprompt
2
+
3
+ [![pub package](https://img.shields.io/npm/v/modprompt)](https://www.npmjs.com/package/modprompt)
4
+
5
+ A collection of prompt templates for language models
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install modprompt
11
+ # or
12
+ yarn add modprompt
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Available templates
18
+
19
+ List the available templates:
20
+
21
+ ```js
22
+ import { templates } from "modprompt";
23
+
24
+ const templateNames = Object.keys(templates);
25
+ console.log(templateNames);
26
+ ```
27
+
28
+ ### Load a template
29
+
30
+ To load a template:
31
+
32
+ ```js
33
+ import { templates, useTemplate } from "modprompt";
34
+
35
+ const tpl = useTemplate(templates.alpaca);
36
+ // or
37
+ const tpl = useTemplate("alpaca");
38
+ ```
39
+
40
+ ### Render a template
41
+
42
+ To render a template to string:
43
+
44
+ ```js
45
+ const templateText = tpl.render();
46
+ ```
47
+
48
+ Rendering for an Alpaca template:
49
+
50
+ ```
51
+ Below is an instruction that describes a task. Write a response that appropriately completes the request.
52
+
53
+ ### Instruction:
54
+ {prompt}
55
+
56
+ ### Response:
57
+ ```
58
+
59
+ ### Render a prompt
60
+
61
+ Similar to the `render` function above, but replaces `{prompt}` by the provided text:
62
+
63
+ ```js
64
+ const templateText = tpl.prompt("What is the capital of Kenya?");
65
+ ```
66
+
67
+ ### System messages
68
+
69
+ The template have system messages support if the original template supports it.
70
+
71
+ To replace a system message:
72
+
73
+ ```js
74
+ tpl.system("You are a javascript specialist");
75
+ ```
76
+
77
+ Rendering for an Alpaca template:
78
+
79
+ ```
80
+ You are a javascript specialist
81
+
82
+ ### Instruction:
83
+ {prompt}
84
+
85
+ ### Response:
86
+ ```
87
+
88
+ To append to a system message:
89
+
90
+ ```js
91
+ tpl.afterSystem("You are a javascript specialist");
92
+ ```
93
+
94
+ ### Example shots
95
+
96
+ The templates have support for example shots. Add one shot:
97
+
98
+ ```js
99
+ tpl.addShot(
100
+ "fix this invalid json:\n\n```json\n{'a':1,}\n```",
101
+ '\n\n```json\n{"a":1}\n```\n',
102
+ )
103
+ ```
104
+
105
+ The first param is the user question, and the second is the assistant response. It
106
+ is assembled in a prompt template. Example with custom user and assistant messages:
107
+
108
+ ```js
109
+ // modify system message
110
+ tpl.afterSystem("You are a javascript specialist");
111
+ // modify assistant message
112
+ tpl.template.assistant = tpl.template.assistant + " (answer in valid json)"
113
+ // modify the prompt message
114
+ tpl.template.user = tpl.template.user.replace("{prompt}", "fix this invalid json:\n\n```json\n{prompt}\n```")
115
+ // add a one shot example
116
+ tpl.addShot(
117
+ "{'a':1,}",
118
+ '\n\n```json\n{"a":1}\n```\n',
119
+ )
120
+ ```
121
+
122
+ Rendering for an Alpaca template:
123
+
124
+ ```
125
+ Below is an instruction that describes a task. Write a response that appropriately completes the request. You are a javascript specialist
126
+
127
+ ### Instruction:
128
+ fix this invalid json:
129
+
130
+ '''json
131
+ {'a':1,}
132
+ '''
133
+
134
+ ### Response: (answer in valid json)
135
+
136
+ '''json
137
+ {"a":1}
138
+ '''
139
+
140
+ ### Instruction:
141
+ fix this invalid json:
142
+
143
+ '''json
144
+ {prompt}
145
+ '''
146
+
147
+ ### Response: (answer in valid json)
148
+ ```
149
+
150
+ ## Types
151
+
152
+ Template types:
153
+
154
+ ```ts
155
+ interface SpacingSlots {
156
+ system?: number;
157
+ user?: number;
158
+ assistant?: number;
159
+ }
160
+
161
+ interface PromptBlock {
162
+ schema: string;
163
+ message?: string;
164
+ }
165
+
166
+ interface TurnBlock {
167
+ user: string;
168
+ assistant: string;
169
+ }
170
+
171
+ interface LmTemplate {
172
+ name: string;
173
+ user: string;
174
+ assistant: string;
175
+ system?: PromptBlock;
176
+ shots?: Array<TurnBlock>;
177
+ stop?: Array<string>;
178
+ linebreaks?: SpacingSlots;
179
+ spacing?: SpacingSlots;
180
+ }
181
+ ```
182
+
183
+ Example raw template:
184
+
185
+ ```ts
186
+ import type { LmTemplate } from "modprompt";
187
+
188
+ const orca: LmTemplate = {
189
+ "name": "Orca",
190
+ "system": {
191
+ "schema": "### System:\n{system}",
192
+ "message": "You are an AI assistant that follows instruction extremely well. Help as much as you can.",
193
+ },
194
+ "user": "### User:\n{prompt}",
195
+ "assistant": "### Response:",
196
+ "linebreaks": {
197
+ "system": 2,
198
+ "user": 2
199
+ }
200
+ }
201
+ ```
package/dist/db.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { LmTemplate } from "./interfaces";
2
+ declare const templates: Record<string, LmTemplate>;
3
+ export { templates };
@@ -0,0 +1,24 @@
1
+ interface SpacingSlots {
2
+ system?: number;
3
+ user?: number;
4
+ assistant?: number;
5
+ }
6
+ interface PromptBlock {
7
+ schema: string;
8
+ message?: string;
9
+ }
10
+ interface TurnBlock {
11
+ user: string;
12
+ assistant: string;
13
+ }
14
+ interface LmTemplate {
15
+ name: string;
16
+ user: string;
17
+ assistant: string;
18
+ system?: PromptBlock;
19
+ shots?: Array<TurnBlock>;
20
+ stop?: Array<string>;
21
+ linebreaks?: SpacingSlots;
22
+ spacing?: SpacingSlots;
23
+ }
24
+ export { SpacingSlots, PromptBlock, TurnBlock, LmTemplate };
package/dist/main.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { templates } from "./db.js";
2
+ import { useTemplate } from "./template.js";
3
+ import type { SpacingSlots, PromptBlock, TurnBlock, LmTemplate } from "@/interfaces.js";
4
+ export { templates, useTemplate };
5
+ export type { SpacingSlots, PromptBlock, TurnBlock, LmTemplate };
@@ -0,0 +1 @@
1
+ "use strict";const s={alpaca:{name:"Alpaca",system:{schema:"{system}",message:"Below is an instruction that describes a task. Write a response that appropriately completes the request."},user:"### Instruction:\n{prompt}",assistant:"### Response:",linebreaks:{system:2,user:2}},orca:{name:"Orca",system:{schema:"### System:\n{system}",message:"You are an AI assistant that follows instruction extremely well. Help as much as you can."},user:"### User:\n{prompt}",assistant:"### Response:",linebreaks:{system:2,user:2}},wizard_vicuna:{name:"Wizard Vicuna",user:"### Human:\n{prompt}",assistant:"### ASSISTANT:",linebreaks:{user:2},stop:["<|endoftext|>"]},chatml:{name:"ChatMl",system:{schema:"<|im_start|>system\n{system}\n<|im_end|>"},user:"<|im_start|>user\n{prompt}<|im_end|>",assistant:"<|im_start|>assistant",linebreaks:{system:1,user:1,assistant:1}}};exports.templates=s,exports.useTemplate=e=>{let t=s.alpaca,a="";function r(s){let e="";if(!t?.system)throw new Error(`The template ${t.name} has no system var`);return e=s?t.system.schema.replace("{system}",s):t.system?.message?t.system.schema.replace("{system}",t.system.message):t.system.schema,e}function n(s){let e=[];return e.push(t.user),t?.spacing?.user&&e.push(" ".repeat(t.spacing.user)),t?.linebreaks?.user&&e.push("\n".repeat(t.linebreaks.user)),s&&(e[0]=e[0].replace("{prompt}",s)),e.join("")}function m(s){let e=[];return e.push(t.assistant),t?.spacing?.assistant&&e.push(" ".repeat(t.spacing.assistant)),t?.linebreaks?.assistant&&e.push("\n".repeat(t.linebreaks.assistant)),s&&(e[0]=e[0]+s+"\n"),e.join("")}e&&("string"==typeof e?function(e){try{if(!(e in s))throw new Error(`Template ${e} not found`);console.log("Loading",e),t=s[e]}catch(s){throw new Error(`Error loading template ${e}`)}t?.system&&(a=r())}(e):(t=e,t?.system&&(a=r())));const p=()=>{const s=new Array;if(a.length>0&&(s.push(a),t?.spacing?.system&&s.push(" ".repeat(t.spacing.system)),t?.linebreaks?.system&&s.push("\n".repeat(t.linebreaks.system))),t?.shots)for(const e of t.shots)s.push(n(e.user)),s.push(m(e.assistant));return s.push(n()),s.push(m()),s.join("")};return{template:t,system:s=>{a=r(s)},afterSystem:s=>{if(!t.system)throw new Error("This template has no system var");t.system?.message||(t.system.message=""),a=r(t.system.message+" "+s)},render:p,prompt:s=>p().replace("{prompt}",s),addShot:(s,e)=>{t?.shots||(t.shots=[]),t.shots.push({user:s,assistant:e})}}};
package/dist/mod.es.js ADDED
@@ -0,0 +1,184 @@
1
+ const templates = {
2
+ "alpaca": {
3
+ "name": "Alpaca",
4
+ "system": {
5
+ "schema": "{system}",
6
+ "message": "Below is an instruction that describes a task. Write a response that appropriately completes the request.",
7
+ },
8
+ "user": "### Instruction:\n{prompt}",
9
+ "assistant": "### Response:",
10
+ "linebreaks": {
11
+ "system": 2,
12
+ "user": 2
13
+ }
14
+ },
15
+ "orca": {
16
+ "name": "Orca",
17
+ "system": {
18
+ "schema": "### System:\n{system}",
19
+ "message": "You are an AI assistant that follows instruction extremely well. Help as much as you can.",
20
+ },
21
+ "user": "### User:\n{prompt}",
22
+ "assistant": "### Response:",
23
+ "linebreaks": {
24
+ "system": 2,
25
+ "user": 2
26
+ }
27
+ },
28
+ "wizard_vicuna": {
29
+ "name": "Wizard Vicuna",
30
+ "user": "### Human:\n{prompt}",
31
+ "assistant": "### ASSISTANT:",
32
+ "linebreaks": {
33
+ "user": 2
34
+ },
35
+ "stop": ["<|endoftext|>"]
36
+ },
37
+ "chatml": {
38
+ "name": "ChatMl",
39
+ "system": {
40
+ "schema": "<|im_start|>system\n{system}\n<|im_end|>",
41
+ },
42
+ "user": "<|im_start|>user\n{prompt}<|im_end|>",
43
+ "assistant": "<|im_start|>assistant",
44
+ "linebreaks": {
45
+ "system": 1,
46
+ "user": 1,
47
+ "assistant": 1,
48
+ }
49
+ },
50
+ };
51
+
52
+ const useTemplate = (_template) => {
53
+ let template = templates.alpaca;
54
+ let _systemBlock = "";
55
+ if (_template) {
56
+ if (typeof _template == "string") {
57
+ load(_template);
58
+ }
59
+ else {
60
+ template = _template;
61
+ if (template?.system) {
62
+ _systemBlock = _buildSystemBlock();
63
+ }
64
+ }
65
+ }
66
+ function load(name) {
67
+ try {
68
+ if (name in templates) {
69
+ console.log("Loading", name);
70
+ template = templates[name];
71
+ }
72
+ else {
73
+ throw new Error(`Template ${name} not found`);
74
+ }
75
+ }
76
+ catch (err) {
77
+ throw new Error(`Error loading template ${name}`);
78
+ }
79
+ if (template?.system) {
80
+ _systemBlock = _buildSystemBlock();
81
+ }
82
+ }
83
+ function _buildSystemBlock(systemMsg) {
84
+ let res = "";
85
+ if (!template?.system) {
86
+ throw new Error(`The template ${template.name} has no system var`);
87
+ }
88
+ if (systemMsg) {
89
+ res = template.system.schema.replace("{system}", systemMsg);
90
+ }
91
+ else {
92
+ if (template.system?.message) {
93
+ res = template.system.schema.replace("{system}", template.system.message);
94
+ }
95
+ else {
96
+ res = template.system.schema;
97
+ }
98
+ }
99
+ return res;
100
+ }
101
+ function _buildUserBlock(msg) {
102
+ let buf = [];
103
+ buf.push(template.user);
104
+ if (template?.spacing?.user) {
105
+ buf.push(" ".repeat(template.spacing.user));
106
+ }
107
+ if (template?.linebreaks?.user) {
108
+ buf.push("\n".repeat(template.linebreaks.user));
109
+ }
110
+ if (msg) {
111
+ buf[0] = buf[0].replace("{prompt}", msg);
112
+ }
113
+ return buf.join("");
114
+ }
115
+ function _buildAssistantBlock(msg) {
116
+ let buf = [];
117
+ buf.push(template.assistant);
118
+ if (template?.spacing?.assistant) {
119
+ buf.push(" ".repeat(template.spacing.assistant));
120
+ }
121
+ if (template?.linebreaks?.assistant) {
122
+ buf.push("\n".repeat(template.linebreaks.assistant));
123
+ }
124
+ if (msg) {
125
+ buf[0] = buf[0] + msg + "\n";
126
+ }
127
+ return buf.join("");
128
+ }
129
+ const addShot = (user, assistant) => {
130
+ if (!template?.shots) {
131
+ template.shots = [];
132
+ }
133
+ template.shots.push({
134
+ user: user,
135
+ assistant: assistant,
136
+ });
137
+ };
138
+ const system = (msg) => {
139
+ _systemBlock = _buildSystemBlock(msg);
140
+ };
141
+ const afterSystem = (msg) => {
142
+ if (!template.system) {
143
+ throw new Error("This template has no system var");
144
+ }
145
+ if (!template.system?.message) {
146
+ template.system.message = "";
147
+ }
148
+ _systemBlock = _buildSystemBlock(template.system.message + " " + msg);
149
+ };
150
+ const render = () => {
151
+ const buf = new Array();
152
+ if (_systemBlock.length > 0) {
153
+ buf.push(_systemBlock);
154
+ if (template?.spacing?.system) {
155
+ buf.push(" ".repeat(template.spacing.system));
156
+ }
157
+ if (template?.linebreaks?.system) {
158
+ buf.push("\n".repeat(template.linebreaks.system));
159
+ }
160
+ }
161
+ if (template?.shots) {
162
+ for (const shot of template.shots) {
163
+ buf.push(_buildUserBlock(shot.user));
164
+ buf.push(_buildAssistantBlock(shot.assistant));
165
+ }
166
+ }
167
+ buf.push(_buildUserBlock());
168
+ buf.push(_buildAssistantBlock());
169
+ return buf.join("");
170
+ };
171
+ const prompt = (msg) => {
172
+ return render().replace("{prompt}", msg);
173
+ };
174
+ return {
175
+ template,
176
+ system,
177
+ afterSystem,
178
+ render,
179
+ prompt,
180
+ addShot,
181
+ };
182
+ };
183
+
184
+ export { templates, useTemplate };
@@ -0,0 +1 @@
1
+ var $tpl=function(s){"use strict";const e={alpaca:{name:"Alpaca",system:{schema:"{system}",message:"Below is an instruction that describes a task. Write a response that appropriately completes the request."},user:"### Instruction:\n{prompt}",assistant:"### Response:",linebreaks:{system:2,user:2}},orca:{name:"Orca",system:{schema:"### System:\n{system}",message:"You are an AI assistant that follows instruction extremely well. Help as much as you can."},user:"### User:\n{prompt}",assistant:"### Response:",linebreaks:{system:2,user:2}},wizard_vicuna:{name:"Wizard Vicuna",user:"### Human:\n{prompt}",assistant:"### ASSISTANT:",linebreaks:{user:2},stop:["<|endoftext|>"]},chatml:{name:"ChatMl",system:{schema:"<|im_start|>system\n{system}\n<|im_end|>"},user:"<|im_start|>user\n{prompt}<|im_end|>",assistant:"<|im_start|>assistant",linebreaks:{system:1,user:1,assistant:1}}};return s.templates=e,s.useTemplate=s=>{let t=e.alpaca,a="";function r(s){let e="";if(!t?.system)throw new Error(`The template ${t.name} has no system var`);return e=s?t.system.schema.replace("{system}",s):t.system?.message?t.system.schema.replace("{system}",t.system.message):t.system.schema,e}function n(s){let e=[];return e.push(t.user),t?.spacing?.user&&e.push(" ".repeat(t.spacing.user)),t?.linebreaks?.user&&e.push("\n".repeat(t.linebreaks.user)),s&&(e[0]=e[0].replace("{prompt}",s)),e.join("")}function m(s){let e=[];return e.push(t.assistant),t?.spacing?.assistant&&e.push(" ".repeat(t.spacing.assistant)),t?.linebreaks?.assistant&&e.push("\n".repeat(t.linebreaks.assistant)),s&&(e[0]=e[0]+s+"\n"),e.join("")}s&&("string"==typeof s?function(s){try{if(!(s in e))throw new Error(`Template ${s} not found`);console.log("Loading",s),t=e[s]}catch(e){throw new Error(`Error loading template ${s}`)}t?.system&&(a=r())}(s):(t=s,t?.system&&(a=r())));const i=()=>{const s=new Array;if(a.length>0&&(s.push(a),t?.spacing?.system&&s.push(" ".repeat(t.spacing.system)),t?.linebreaks?.system&&s.push("\n".repeat(t.linebreaks.system))),t?.shots)for(const e of t.shots)s.push(n(e.user)),s.push(m(e.assistant));return s.push(n()),s.push(m()),s.join("")};return{template:t,system:s=>{a=r(s)},afterSystem:s=>{if(!t.system)throw new Error("This template has no system var");t.system?.message||(t.system.message=""),a=r(t.system.message+" "+s)},render:i,prompt:s=>i().replace("{prompt}",s),addShot:(s,e)=>{t?.shots||(t.shots=[]),t.shots.push({user:s,assistant:e})}}},s}({});
@@ -0,0 +1,10 @@
1
+ import { LmTemplate } from "./interfaces.js";
2
+ declare const useTemplate: (_template?: string | LmTemplate) => {
3
+ template: LmTemplate;
4
+ system: (msg: string) => void;
5
+ afterSystem: (msg: string) => void;
6
+ render: () => string;
7
+ prompt: (msg: string) => string;
8
+ addShot: (user: string, assistant: string) => void;
9
+ };
10
+ export { useTemplate };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "modprompt",
3
+ "version": "0.0.1",
4
+ "description": "Prompt templates for language models",
5
+ "license": "MIT",
6
+ "scripts": {
7
+ "build": "rm -rf dist/* && rollup -c",
8
+ "test": "jest --coverage",
9
+ "docs": "typedoc --entryPointStrategy expand"
10
+ },
11
+ "dependencies": {},
12
+ "devDependencies": {
13
+ "@rollup/plugin-commonjs": "^25.0.4",
14
+ "@rollup/plugin-node-resolve": "^15.2.1",
15
+ "@rollup/plugin-typescript": "^11.1.3",
16
+ "@types/node": "^20.6.0",
17
+ "rollup": "^3.29.0",
18
+ "rollup-plugin-terser": "^7.0.2",
19
+ "tslib": "^2.6.2",
20
+ "typescript": "^4.9.5"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "main": "./dist/mod.cjs.min.js",
26
+ "module": "./dist/mod.es.js",
27
+ "types": "./dist/main.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "import": "./dist/mod.es.js",
31
+ "require": "./dist/mod.cjs.min.js"
32
+ }
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org/"
37
+ }
38
+ }