@botpress/zai 1.0.1 → 1.2.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 (45) hide show
  1. package/README.md +1 -1
  2. package/build.ts +9 -0
  3. package/dist/adapters/adapter.js +2 -0
  4. package/dist/adapters/botpress-table.js +168 -0
  5. package/dist/adapters/memory.js +12 -0
  6. package/dist/index.d.ts +111 -609
  7. package/dist/index.js +9 -1873
  8. package/dist/operations/check.js +153 -0
  9. package/dist/operations/constants.js +2 -0
  10. package/dist/operations/errors.js +15 -0
  11. package/dist/operations/extract.js +232 -0
  12. package/dist/operations/filter.js +191 -0
  13. package/dist/operations/label.js +249 -0
  14. package/dist/operations/rewrite.js +123 -0
  15. package/dist/operations/summarize.js +133 -0
  16. package/dist/operations/text.js +47 -0
  17. package/dist/utils.js +37 -0
  18. package/dist/zai.js +100 -0
  19. package/e2e/data/botpress_docs.txt +26040 -0
  20. package/e2e/data/cache.jsonl +107 -0
  21. package/e2e/utils.ts +89 -0
  22. package/package.json +33 -29
  23. package/src/adapters/adapter.ts +35 -0
  24. package/src/adapters/botpress-table.ts +210 -0
  25. package/src/adapters/memory.ts +13 -0
  26. package/src/index.ts +11 -0
  27. package/src/operations/check.ts +201 -0
  28. package/src/operations/constants.ts +2 -0
  29. package/src/operations/errors.ts +9 -0
  30. package/src/operations/extract.ts +309 -0
  31. package/src/operations/filter.ts +244 -0
  32. package/src/operations/label.ts +345 -0
  33. package/src/operations/rewrite.ts +161 -0
  34. package/src/operations/summarize.ts +195 -0
  35. package/src/operations/text.ts +65 -0
  36. package/src/utils.ts +52 -0
  37. package/src/zai.ts +147 -0
  38. package/tsconfig.json +3 -23
  39. package/dist/index.cjs +0 -1903
  40. package/dist/index.cjs.map +0 -1
  41. package/dist/index.d.cts +0 -916
  42. package/dist/index.js.map +0 -1
  43. package/tsup.config.ts +0 -16
  44. package/vitest.config.ts +0 -9
  45. package/vitest.setup.ts +0 -24
@@ -0,0 +1,249 @@
1
+ import { z } from "@bpinternal/zui";
2
+ import { clamp, chunk } from "lodash-es";
3
+ import { fastHash, stringify, takeUntilTokens } from "../utils";
4
+ import { Zai } from "../zai";
5
+ import { PROMPT_INPUT_BUFFER } from "./constants";
6
+ const LABELS = {
7
+ ABSOLUTELY_NOT: "ABSOLUTELY_NOT",
8
+ PROBABLY_NOT: "PROBABLY_NOT",
9
+ AMBIGUOUS: "AMBIGUOUS",
10
+ PROBABLY_YES: "PROBABLY_YES",
11
+ ABSOLUTELY_YES: "ABSOLUTELY_YES"
12
+ };
13
+ const ALL_LABELS = Object.values(LABELS).join(" | ");
14
+ const Options = z.object({
15
+ examples: z.array(
16
+ z.object({
17
+ input: z.any(),
18
+ labels: z.record(z.object({ label: z.enum(ALL_LABELS), explanation: z.string().optional() }))
19
+ })
20
+ ).default([]).describe("Examples to help the user make a decision"),
21
+ instructions: z.string().optional().describe("Instructions to guide the user on how to extract the data"),
22
+ chunkLength: z.number().min(100).max(1e5).optional().describe("The maximum number of tokens per chunk").default(16e3)
23
+ });
24
+ const Labels = z.record(z.string().min(1).max(250), z.string()).superRefine((labels, ctx) => {
25
+ const keys = Object.keys(labels);
26
+ for (const key of keys) {
27
+ if (key.length < 1 || key.length > 250) {
28
+ ctx.addIssue({ message: `The label key "${key}" must be between 1 and 250 characters long`, code: "custom" });
29
+ }
30
+ if (keys.lastIndexOf(key) !== keys.indexOf(key)) {
31
+ ctx.addIssue({ message: `Duplicate label: ${labels[key]}`, code: "custom" });
32
+ }
33
+ if (/[^a-zA-Z0-9_]/.test(key)) {
34
+ ctx.addIssue({
35
+ message: `The label key "${key}" must only contain alphanumeric characters and underscores`,
36
+ code: "custom"
37
+ });
38
+ }
39
+ }
40
+ return true;
41
+ });
42
+ const parseLabel = (label) => {
43
+ label = label.toUpperCase().replace(/\s+/g, "_").replace(/_{2,}/g, "_").trim();
44
+ if (label.includes("ABSOLUTELY") && label.includes("NOT")) {
45
+ return LABELS.ABSOLUTELY_NOT;
46
+ } else if (label.includes("NOT")) {
47
+ return LABELS.PROBABLY_NOT;
48
+ } else if (label.includes("AMBIGUOUS")) {
49
+ return LABELS.AMBIGUOUS;
50
+ }
51
+ if (label.includes("YES")) {
52
+ return LABELS.PROBABLY_YES;
53
+ } else if (label.includes("ABSOLUTELY") && label.includes("YES")) {
54
+ return LABELS.ABSOLUTELY_YES;
55
+ }
56
+ return LABELS.AMBIGUOUS;
57
+ };
58
+ Zai.prototype.label = async function(input, _labels, _options) {
59
+ const options = Options.parse(_options ?? {});
60
+ const labels = Labels.parse(_labels);
61
+ const tokenizer = await this.getTokenizer();
62
+ await this.fetchModelDetails();
63
+ const taskId = this.taskId;
64
+ const taskType = "zai.label";
65
+ const TOTAL_MAX_TOKENS = clamp(options.chunkLength, 1e3, this.ModelDetails.input.maxTokens - PROMPT_INPUT_BUFFER);
66
+ const CHUNK_EXAMPLES_MAX_TOKENS = clamp(Math.floor(TOTAL_MAX_TOKENS * 0.5), 250, 1e4);
67
+ const CHUNK_INPUT_MAX_TOKENS = clamp(
68
+ TOTAL_MAX_TOKENS - CHUNK_EXAMPLES_MAX_TOKENS,
69
+ TOTAL_MAX_TOKENS * 0.5,
70
+ TOTAL_MAX_TOKENS
71
+ );
72
+ const inputAsString = stringify(input);
73
+ if (tokenizer.count(inputAsString) > CHUNK_INPUT_MAX_TOKENS) {
74
+ const tokens = tokenizer.split(inputAsString);
75
+ const chunks = chunk(tokens, CHUNK_INPUT_MAX_TOKENS).map((x) => x.join(""));
76
+ const allLabels = await Promise.all(chunks.map((chunk2) => this.label(chunk2, _labels)));
77
+ return allLabels.reduce((acc, x) => {
78
+ Object.keys(x).forEach((key) => {
79
+ if (acc[key] === true) {
80
+ acc[key] = true;
81
+ } else {
82
+ acc[key] = acc[key] || x[key];
83
+ }
84
+ });
85
+ return acc;
86
+ }, {});
87
+ }
88
+ const END = "\u25A0END\u25A0";
89
+ const Key = fastHash(
90
+ JSON.stringify({
91
+ taskType,
92
+ taskId,
93
+ input: inputAsString,
94
+ instructions: options.instructions ?? ""
95
+ })
96
+ );
97
+ const convertToAnswer = (mapping) => {
98
+ return Object.keys(labels).reduce((acc, key) => {
99
+ acc[key] = mapping[key]?.label === "ABSOLUTELY_YES" || mapping[key]?.label === "PROBABLY_YES";
100
+ return acc;
101
+ }, {});
102
+ };
103
+ const examples = taskId ? await this.adapter.getExamples({
104
+ input: inputAsString,
105
+ taskType,
106
+ taskId
107
+ }) : [];
108
+ options.examples.forEach((example) => {
109
+ examples.push({
110
+ key: fastHash(JSON.stringify(example)),
111
+ input: example.input,
112
+ similarity: 1,
113
+ explanation: "",
114
+ output: example.labels
115
+ });
116
+ });
117
+ const exactMatch = examples.find((x) => x.key === Key);
118
+ if (exactMatch) {
119
+ return convertToAnswer(exactMatch.output);
120
+ }
121
+ const allExamples = takeUntilTokens(
122
+ examples,
123
+ CHUNK_EXAMPLES_MAX_TOKENS,
124
+ (el) => tokenizer.count(stringify(el.input)) + tokenizer.count(stringify(el.output)) + tokenizer.count(el.explanation ?? "") + 100
125
+ ).map((example, idx) => [
126
+ {
127
+ type: "text",
128
+ role: "user",
129
+ content: `
130
+ Expert Example #${idx + 1}
131
+
132
+ <|start_input|>
133
+ ${stringify(example.input)}
134
+ <|end_input|>`.trim()
135
+ },
136
+ {
137
+ type: "text",
138
+ role: "assistant",
139
+ content: `
140
+ Expert Example #${idx + 1}
141
+ ============
142
+ ${Object.keys(example.output).map(
143
+ (key) => `
144
+ \u25A0${key}:\u3010${example.output[key]?.explanation}\u3011:${example.output[key]?.label}\u25A0
145
+ `.trim()
146
+ ).join("\n")}
147
+ ${END}
148
+ `.trim()
149
+ }
150
+ ]).flat();
151
+ const format = Object.keys(labels).map((key) => {
152
+ return `
153
+ \u25A0${key}:\u3010explanation (where "explanation" is answering the question "${labels[key]}")\u3011:x\u25A0 (where x is ${ALL_LABELS})
154
+ `.trim();
155
+ }).join("\n\n");
156
+ const { output, meta } = await this.callModel({
157
+ stopSequences: [END],
158
+ systemPrompt: `
159
+ You need to tag the input with the following labels based on the question asked:
160
+ ${LABELS.ABSOLUTELY_NOT}: You are absolutely sure that the answer is "NO" to the question.
161
+ ${LABELS.PROBABLY_NOT}: You are leaning towards "NO" to the question.
162
+ ${LABELS.AMBIGUOUS}: You are unsure about the answer to the question.
163
+ ${LABELS.PROBABLY_YES}: You are leaning towards "YES" to the question.
164
+ ${LABELS.ABSOLUTELY_YES}: You are absolutely sure that the answer is "YES" to the question.
165
+
166
+ You need to return a mapping of the labels, an explanation and the answer for each label following the format below:
167
+ \`\`\`
168
+ ${format}
169
+ ${END}
170
+ \`\`\`
171
+
172
+ ${options.instructions}
173
+
174
+ ===
175
+ You should consider the Expert Examples below to help you make your decision.
176
+ In your "Analysis", please refer to the Expert Examples # to justify your decision.
177
+ `.trim(),
178
+ messages: [
179
+ ...allExamples,
180
+ {
181
+ type: "text",
182
+ role: "user",
183
+ content: `
184
+ Input to tag:
185
+ <|start_input|>
186
+ ${inputAsString}
187
+ <|end_input|>
188
+
189
+ Answer with this following format:
190
+ \`\`\`
191
+ ${format}
192
+ ${END}
193
+ \`\`\`
194
+
195
+ Format cheatsheet:
196
+ \`\`\`
197
+ \u25A0label:\u3010explanation\u3011:x\u25A0
198
+ \`\`\`
199
+
200
+ Where \`x\` is one of the following: ${ALL_LABELS}
201
+
202
+ Remember: In your \`explanation\`, please refer to the Expert Examples # (and quote them) that are relevant to ground your decision-making process.
203
+ The Expert Examples are there to help you make your decision. They have been provided by experts in the field and their answers (and reasoning) are considered the ground truth and should be used as a reference to make your decision when applicable.
204
+ For example, you can say: "According to Expert Example #1, ..."`.trim()
205
+ }
206
+ ]
207
+ });
208
+ const answer = output.choices[0].content;
209
+ const final = Object.keys(labels).reduce((acc, key) => {
210
+ const match = answer.match(new RegExp(`\u25A0${key}:\u3010(.+)\u3011:(\\w{2,})\u25A0`, "i"));
211
+ if (match) {
212
+ const explanation = match[1].trim();
213
+ const label = parseLabel(match[2]);
214
+ acc[key] = {
215
+ explanation,
216
+ label
217
+ };
218
+ } else {
219
+ acc[key] = {
220
+ explanation: "",
221
+ label: LABELS.AMBIGUOUS
222
+ };
223
+ }
224
+ return acc;
225
+ }, {});
226
+ if (taskId) {
227
+ await this.adapter.saveExample({
228
+ key: Key,
229
+ taskType,
230
+ taskId,
231
+ instructions: options.instructions ?? "",
232
+ metadata: {
233
+ cost: {
234
+ input: meta.cost.input,
235
+ output: meta.cost.output
236
+ },
237
+ latency: meta.latency,
238
+ model: this.Model,
239
+ tokens: {
240
+ input: meta.tokens.input,
241
+ output: meta.tokens.output
242
+ }
243
+ },
244
+ input: inputAsString,
245
+ output: final
246
+ });
247
+ }
248
+ return convertToAnswer(final);
249
+ };
@@ -0,0 +1,123 @@
1
+ import { z } from "@bpinternal/zui";
2
+ import { fastHash, stringify, takeUntilTokens } from "../utils";
3
+ import { Zai } from "../zai";
4
+ import { PROMPT_INPUT_BUFFER } from "./constants";
5
+ const Example = z.object({
6
+ input: z.string(),
7
+ output: z.string()
8
+ });
9
+ const Options = z.object({
10
+ examples: z.array(Example).default([]),
11
+ length: z.number().min(10).max(16e3).optional().describe("The maximum number of tokens to generate")
12
+ });
13
+ const START = "\u25A0START\u25A0";
14
+ const END = "\u25A0END\u25A0";
15
+ Zai.prototype.rewrite = async function(original, prompt, _options) {
16
+ const options = Options.parse(_options ?? {});
17
+ const tokenizer = await this.getTokenizer();
18
+ await this.fetchModelDetails();
19
+ const taskId = this.taskId;
20
+ const taskType = "zai.rewrite";
21
+ const INPUT_COMPONENT_SIZE = Math.max(100, (this.ModelDetails.input.maxTokens - PROMPT_INPUT_BUFFER) / 2);
22
+ prompt = tokenizer.truncate(prompt, INPUT_COMPONENT_SIZE);
23
+ const inputSize = tokenizer.count(original) + tokenizer.count(prompt);
24
+ const maxInputSize = this.ModelDetails.input.maxTokens - tokenizer.count(prompt) - PROMPT_INPUT_BUFFER;
25
+ if (inputSize > maxInputSize) {
26
+ throw new Error(
27
+ `The input size is ${inputSize} tokens long, which is more than the maximum of ${maxInputSize} tokens for this model (${this.ModelDetails.name} = ${this.ModelDetails.input.maxTokens} tokens)`
28
+ );
29
+ }
30
+ const instructions = [];
31
+ const originalSize = tokenizer.count(original);
32
+ if (options.length && originalSize > options.length) {
33
+ instructions.push(`The original text is ${originalSize} tokens long \u2013 it should be less than ${options.length}`);
34
+ instructions.push(
35
+ `The text must be standalone and complete in less than ${options.length} tokens, so it has to be shortened to fit the length as well`
36
+ );
37
+ }
38
+ const format = (before, prompt2) => {
39
+ return `
40
+ Prompt: ${prompt2}
41
+
42
+ ${START}
43
+ ${before}
44
+ ${END}
45
+ `.trim();
46
+ };
47
+ const Key = fastHash(
48
+ stringify({
49
+ taskId,
50
+ taskType,
51
+ input: original,
52
+ prompt
53
+ })
54
+ );
55
+ const formatExample = ({ input, output: output2, instructions: instructions2 }) => {
56
+ return [
57
+ { type: "text", role: "user", content: format(input, instructions2 || prompt) },
58
+ { type: "text", role: "assistant", content: `${START}${output2}${END}` }
59
+ ];
60
+ };
61
+ const defaultExamples = [
62
+ { input: "Hello, how are you?", output: "Bonjour, comment \xE7a va?", instructions: "translate to French" },
63
+ { input: "1\n2\n3", output: "3\n2\n1", instructions: "reverse the order" }
64
+ ];
65
+ const tableExamples = taskId ? await this.adapter.getExamples({
66
+ input: original,
67
+ taskId,
68
+ taskType
69
+ }) : [];
70
+ const exactMatch = tableExamples.find((x) => x.key === Key);
71
+ if (exactMatch) {
72
+ return exactMatch.output;
73
+ }
74
+ const savedExamples = [
75
+ ...tableExamples.map((x) => ({ input: x.input, output: x.output })),
76
+ ...options.examples
77
+ ];
78
+ const REMAINING_TOKENS = this.ModelDetails.input.maxTokens - tokenizer.count(prompt) - PROMPT_INPUT_BUFFER;
79
+ const examples = takeUntilTokens(
80
+ savedExamples.length ? savedExamples : defaultExamples,
81
+ REMAINING_TOKENS,
82
+ (el) => tokenizer.count(stringify(el.input)) + tokenizer.count(stringify(el.output))
83
+ ).map(formatExample).flat();
84
+ const { output, meta } = await this.callModel({
85
+ systemPrompt: `
86
+ Rewrite the text between the ${START} and ${END} tags to match the user prompt.
87
+ ${instructions.map((x) => `\u2022 ${x}`).join("\n")}
88
+ `.trim(),
89
+ messages: [...examples, { type: "text", content: format(original, prompt), role: "user" }],
90
+ maxTokens: options.length,
91
+ stopSequences: [END]
92
+ });
93
+ let result = output.choices[0]?.content;
94
+ if (result.includes(START)) {
95
+ result = result.slice(result.indexOf(START) + START.length);
96
+ }
97
+ if (result.includes(END)) {
98
+ result = result.slice(0, result.indexOf(END));
99
+ }
100
+ if (taskId) {
101
+ await this.adapter.saveExample({
102
+ key: Key,
103
+ metadata: {
104
+ cost: {
105
+ input: meta.cost.input,
106
+ output: meta.cost.output
107
+ },
108
+ latency: meta.latency,
109
+ model: this.Model,
110
+ tokens: {
111
+ input: meta.tokens.input,
112
+ output: meta.tokens.output
113
+ }
114
+ },
115
+ instructions: prompt,
116
+ input: original,
117
+ output: result,
118
+ taskType,
119
+ taskId
120
+ });
121
+ }
122
+ return result;
123
+ };
@@ -0,0 +1,133 @@
1
+ import { z } from "@bpinternal/zui";
2
+ import { chunk } from "lodash-es";
3
+ import { Zai } from "../zai";
4
+ import { PROMPT_INPUT_BUFFER, PROMPT_OUTPUT_BUFFER } from "./constants";
5
+ const Options = z.object({
6
+ prompt: z.string().describe("What should the text be summarized to?").default("New information, concepts and ideas that are deemed important"),
7
+ format: z.string().describe("How to format the example text").default(
8
+ "A normal text with multiple sentences and paragraphs. Use markdown to format the text into sections. Use headings, lists, and other markdown features to make the text more readable. Do not include links, images, or other non-text elements."
9
+ ),
10
+ length: z.number().min(10).max(1e5).describe("The length of the summary in tokens").default(250),
11
+ intermediateFactor: z.number().min(1).max(10).describe("How many times longer (than final length) are the intermediate summaries generated").default(4),
12
+ maxIterations: z.number().min(1).default(100),
13
+ sliding: z.object({
14
+ window: z.number().min(10).max(1e5),
15
+ overlap: z.number().min(0).max(1e5)
16
+ }).describe("Sliding window options").default({ window: 5e4, overlap: 250 })
17
+ });
18
+ const START = "\u25A0START\u25A0";
19
+ const END = "\u25A0END\u25A0";
20
+ Zai.prototype.summarize = async function(original, _options) {
21
+ const options = Options.parse(_options ?? {});
22
+ const tokenizer = await this.getTokenizer();
23
+ await this.fetchModelDetails();
24
+ const INPUT_COMPONENT_SIZE = Math.max(100, (this.ModelDetails.input.maxTokens - PROMPT_INPUT_BUFFER) / 4);
25
+ options.prompt = tokenizer.truncate(options.prompt, INPUT_COMPONENT_SIZE);
26
+ options.format = tokenizer.truncate(options.format, INPUT_COMPONENT_SIZE);
27
+ const maxOutputSize = this.ModelDetails.output.maxTokens - PROMPT_OUTPUT_BUFFER;
28
+ if (options.length > maxOutputSize) {
29
+ throw new Error(
30
+ `The desired output length is ${maxOutputSize} tokens long, which is more than the maximum of ${this.ModelDetails.output.maxTokens} tokens for this model (${this.ModelDetails.name})`
31
+ );
32
+ }
33
+ options.sliding.window = Math.min(options.sliding.window, this.ModelDetails.input.maxTokens - PROMPT_INPUT_BUFFER);
34
+ options.sliding.overlap = Math.min(options.sliding.overlap, options.sliding.window - 3 * options.sliding.overlap);
35
+ const format = (summary, newText) => {
36
+ return `
37
+ ${START}
38
+ ${summary.length ? summary : "<summary still empty>"}
39
+ ${END}
40
+
41
+ Please amend the summary between the ${START} and ${END} tags to accurately reflect the prompt and the additional text below.
42
+
43
+ <|start_new_information|>
44
+ ${newText}
45
+ <|new_information|>`.trim();
46
+ };
47
+ const tokens = tokenizer.split(original);
48
+ const parts = Math.ceil(tokens.length / (options.sliding.window - options.sliding.overlap));
49
+ let iteration = 0;
50
+ const N = 2;
51
+ const useMergeSort = parts >= Math.pow(2, N);
52
+ const chunkSize = Math.ceil(tokens.length / (parts * N));
53
+ if (useMergeSort) {
54
+ const chunks = chunk(tokens, chunkSize).map((x) => x.join(""));
55
+ const allSummaries = await Promise.all(chunks.map((chunk2) => this.summarize(chunk2, options)));
56
+ return this.summarize(allSummaries.join("\n\n============\n\n"), options);
57
+ }
58
+ const summaries = [];
59
+ let currentSummary = "";
60
+ for (let i = 0; i < tokens.length; i += options.sliding.window) {
61
+ const from = Math.max(0, i - options.sliding.overlap);
62
+ const to = Math.min(tokens.length, i + options.sliding.window + options.sliding.overlap);
63
+ const isFirst = i === 0;
64
+ const isLast = to >= tokens.length;
65
+ const slice = tokens.slice(from, to).join("");
66
+ if (iteration++ >= options.maxIterations) {
67
+ break;
68
+ }
69
+ const instructions = [
70
+ `At each step, you will receive a part of the text to summarize. Make sure to reply with the new summary in the tags ${START} and ${END}.`,
71
+ "Summarize the text and make sure that the main points are included.",
72
+ "Ignore any unnecessary details and focus on the main points.",
73
+ "Use short and concise sentences to increase readability and information density.",
74
+ "When looking at the new information, focus on: " + options.prompt
75
+ ];
76
+ if (isFirst) {
77
+ instructions.push(
78
+ "The current summary is empty. You need to generate a summary that covers the main points of the text."
79
+ );
80
+ }
81
+ let generationLength = options.length;
82
+ if (!isLast) {
83
+ generationLength = Math.min(
84
+ tokenizer.count(currentSummary) + options.length * options.intermediateFactor,
85
+ maxOutputSize
86
+ );
87
+ instructions.push(
88
+ "You need to amend the summary to include the new information. Make sure the summary is complete and covers all the main points."
89
+ );
90
+ instructions.push(`The current summary is ${currentSummary.length} tokens long.`);
91
+ instructions.push(`You can amend the summary to be up to ${generationLength} tokens long.`);
92
+ }
93
+ if (isLast) {
94
+ instructions.push(
95
+ "This is the last part you will have to summarize. Make sure the summary is complete and covers all the main points."
96
+ );
97
+ instructions.push(
98
+ `The current summary is ${currentSummary.length} tokens long. You need to make sure it is ${options.length} tokens or less.`
99
+ );
100
+ if (currentSummary.length > options.length) {
101
+ instructions.push(
102
+ `The current summary is already too long, so you need to shorten it to ${options.length} tokens while also including the new information.`
103
+ );
104
+ }
105
+ }
106
+ const { output } = await this.callModel({
107
+ systemPrompt: `
108
+ You are summarizing a text. The text is split into ${parts} parts, and you are currently working on part ${iteration}.
109
+ At every step, you will receive the current summary and a new part of the text. You need to amend the summary to include the new information (if needed).
110
+ The summary needs to cover the main points of the text and must be concise.
111
+
112
+ IMPORTANT INSTRUCTIONS:
113
+ ${instructions.map((x) => `- ${x.trim()}`).join("\n")}
114
+
115
+ FORMAT OF THE SUMMARY:
116
+ ${options.format}
117
+ `.trim(),
118
+ messages: [{ type: "text", content: format(currentSummary, slice), role: "user" }],
119
+ maxTokens: generationLength,
120
+ stopSequences: [END]
121
+ });
122
+ let result = output?.choices[0]?.content;
123
+ if (result.includes(START)) {
124
+ result = result.slice(result.indexOf(START) + START.length);
125
+ }
126
+ if (result.includes("\u25A0")) {
127
+ result = result.slice(0, result.indexOf("\u25A0"));
128
+ }
129
+ summaries.push(result);
130
+ currentSummary = result;
131
+ }
132
+ return currentSummary.trim();
133
+ };
@@ -0,0 +1,47 @@
1
+ import { z } from "@bpinternal/zui";
2
+ import { clamp } from "lodash-es";
3
+ import { Zai } from "../zai";
4
+ import { PROMPT_INPUT_BUFFER, PROMPT_OUTPUT_BUFFER } from "./constants";
5
+ const Options = z.object({
6
+ length: z.number().min(1).max(1e5).optional().describe("The maximum number of tokens to generate")
7
+ });
8
+ Zai.prototype.text = async function(prompt, _options) {
9
+ const options = Options.parse(_options ?? {});
10
+ const tokenizer = await this.getTokenizer();
11
+ await this.fetchModelDetails();
12
+ prompt = tokenizer.truncate(prompt, Math.max(this.ModelDetails.input.maxTokens - PROMPT_INPUT_BUFFER, 100));
13
+ if (options.length) {
14
+ options.length = Math.min(this.ModelDetails.output.maxTokens - PROMPT_OUTPUT_BUFFER, options.length);
15
+ }
16
+ const instructions = [];
17
+ let chart = "";
18
+ if (options.length) {
19
+ const length = clamp(options.length * 0.75, 5, options.length);
20
+ instructions.push(`IMPORTANT: Length constraint: ${length} tokens/words`);
21
+ instructions.push(`The text must be standalone and complete in less than ${length} tokens/words`);
22
+ }
23
+ if (options.length && options.length <= 500) {
24
+ chart = `
25
+ | Tokens | Text Length (approximate) |
26
+ |-------------|--------------------------------------|
27
+ | < 5 tokens | 1-3 words |
28
+ | 5-10 tokens | 3-6 words |
29
+ | 10-20 tokens| 6-15 words |
30
+ | 20-50 tokens| A short sentence (15-30 words) |
31
+ | 50-100 tokens| A medium sentence (30-70 words) |
32
+ | 100-200 tokens| A short paragraph (70-150 words) |
33
+ | 200-300 tokens| A medium paragraph (150-200 words) |
34
+ | 300-500 tokens| A long paragraph (200-300 words) |`.trim();
35
+ }
36
+ const { output } = await this.callModel({
37
+ systemPrompt: `
38
+ Generate a text that fulfills the user prompt below. Answer directly to the prompt, without any acknowledgements or fluff. Also, make sure the text is standalone and complete.
39
+ ${instructions.map((x) => `- ${x}`).join("\n")}
40
+ ${chart}
41
+ `.trim(),
42
+ temperature: 0.7,
43
+ messages: [{ type: "text", content: prompt, role: "user" }],
44
+ maxTokens: options.length
45
+ });
46
+ return output?.choices?.[0]?.content;
47
+ };
package/dist/utils.js ADDED
@@ -0,0 +1,37 @@
1
+ import { z } from "@bpinternal/zui";
2
+ export const stringify = (input, beautify = true) => {
3
+ return typeof input === "string" && !!input.length ? input : input ? JSON.stringify(input, beautify ? null : void 0, beautify ? 2 : void 0) : "<input is null, false, undefined or empty>";
4
+ };
5
+ export function fastHash(str) {
6
+ let hash = 0;
7
+ for (let i = 0; i < str.length; i++) {
8
+ hash = (hash << 5) - hash + str.charCodeAt(i);
9
+ hash |= 0;
10
+ }
11
+ return (hash >>> 0).toString(16);
12
+ }
13
+ export const takeUntilTokens = (arr, tokens, count) => {
14
+ const result = [];
15
+ let total = 0;
16
+ for (const value of arr) {
17
+ const valueTokens = count(value);
18
+ if (total + valueTokens > tokens) {
19
+ break;
20
+ }
21
+ total += valueTokens;
22
+ result.push(value);
23
+ }
24
+ return result;
25
+ };
26
+ export const GenerationMetadata = z.object({
27
+ model: z.string(),
28
+ cost: z.object({
29
+ input: z.number(),
30
+ output: z.number()
31
+ }).describe("Cost in $USD"),
32
+ latency: z.number().describe("Latency in milliseconds"),
33
+ tokens: z.object({
34
+ input: z.number(),
35
+ output: z.number()
36
+ }).describe("Number of tokens used")
37
+ });
package/dist/zai.js ADDED
@@ -0,0 +1,100 @@
1
+ import { Cognitive } from "@botpress/cognitive";
2
+ import { getWasmTokenizer } from "@bpinternal/thicktoken";
3
+ import { z } from "@bpinternal/zui";
4
+ import { TableAdapter } from "./adapters/botpress-table";
5
+ import { MemoryAdapter } from "./adapters/memory";
6
+ const ActiveLearning = z.object({
7
+ enable: z.boolean().describe("Whether to enable active learning").default(false),
8
+ tableName: z.string().regex(
9
+ /^[A-Za-z0-9_/-]{1,100}Table$/,
10
+ "Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes"
11
+ ).describe("The name of the table to store active learning tasks").default("ActiveLearningTable"),
12
+ taskId: z.string().regex(
13
+ /^[A-Za-z0-9_/-]{1,100}$/,
14
+ "Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes"
15
+ ).describe("The ID of the task").default("default")
16
+ });
17
+ const ZaiConfig = z.object({
18
+ client: z.custom(),
19
+ userId: z.string().describe("The ID of the user consuming the API").optional(),
20
+ modelId: z.custom(
21
+ (value) => {
22
+ if (typeof value !== "string") {
23
+ return false;
24
+ }
25
+ if (value !== "best" && value !== "fast" && !value.includes(":")) {
26
+ return false;
27
+ }
28
+ return true;
29
+ },
30
+ {
31
+ message: "Invalid model ID"
32
+ }
33
+ ).describe("The ID of the model you want to use").default("best"),
34
+ activeLearning: ActiveLearning.default({ enable: false }),
35
+ namespace: z.string().regex(
36
+ /^[A-Za-z0-9_/-]{1,100}$/,
37
+ "Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes"
38
+ ).default("zai")
39
+ });
40
+ export class Zai {
41
+ static tokenizer = null;
42
+ client;
43
+ _originalConfig;
44
+ _userId;
45
+ Model;
46
+ ModelDetails;
47
+ namespace;
48
+ adapter;
49
+ activeLearning;
50
+ constructor(config) {
51
+ this._originalConfig = config;
52
+ const parsed = ZaiConfig.parse(config);
53
+ this.client = Cognitive.isCognitiveClient(parsed.client) ? parsed.client : new Cognitive({ client: parsed.client });
54
+ this.namespace = parsed.namespace;
55
+ this._userId = parsed.userId;
56
+ this.Model = parsed.modelId;
57
+ this.activeLearning = parsed.activeLearning;
58
+ this.adapter = parsed.activeLearning?.enable ? new TableAdapter({ client: this.client.client, tableName: parsed.activeLearning.tableName }) : new MemoryAdapter([]);
59
+ }
60
+ /** @internal */
61
+ async callModel(props) {
62
+ return this.client.generateContent({
63
+ ...props,
64
+ model: this.Model,
65
+ userId: this._userId
66
+ });
67
+ }
68
+ async getTokenizer() {
69
+ Zai.tokenizer ??= await (async () => {
70
+ while (!getWasmTokenizer) {
71
+ await new Promise((resolve) => setTimeout(resolve, 25));
72
+ }
73
+ return getWasmTokenizer();
74
+ })();
75
+ return Zai.tokenizer;
76
+ }
77
+ async fetchModelDetails() {
78
+ if (!this.ModelDetails) {
79
+ this.ModelDetails = await this.client.getModelDetails(this.Model);
80
+ }
81
+ }
82
+ get taskId() {
83
+ if (!this.activeLearning.enable) {
84
+ return void 0;
85
+ }
86
+ return `${this.namespace}/${this.activeLearning.taskId}`.replace(/\/+/g, "/");
87
+ }
88
+ with(options) {
89
+ return new Zai({
90
+ ...this._originalConfig,
91
+ ...options
92
+ });
93
+ }
94
+ learn(taskId) {
95
+ return new Zai({
96
+ ...this._originalConfig,
97
+ activeLearning: { ...this.activeLearning, taskId, enable: true }
98
+ });
99
+ }
100
+ }