@botpress/zai 1.0.1-beta.1 → 1.0.1-beta.3

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 (47) hide show
  1. package/dist/browser/index.js +4071 -0
  2. package/dist/{csj → node}/adapters/botpress-table.js +1 -2
  3. package/dist/{csj → node}/operations/check.js +1 -2
  4. package/dist/{csj → node}/operations/extract.js +8 -9
  5. package/dist/{csj → node}/operations/filter.js +4 -5
  6. package/dist/{csj → node}/operations/label.js +7 -8
  7. package/dist/{csj → node}/operations/rewrite.js +1 -2
  8. package/dist/{csj → node}/operations/summarize.js +4 -5
  9. package/dist/{csj → node}/operations/text.js +3 -4
  10. package/dist/{csj → node}/utils.js +1 -2
  11. package/dist/{csj → node}/zai.js +1 -2
  12. package/package.json +17 -12
  13. package/scripts/update-models.mts +3 -3
  14. package/scripts/update-types.mts +5 -15
  15. package/src/adapters/botpress-table.ts +3 -4
  16. package/src/operations/__tests/index.ts +1 -0
  17. package/src/operations/check.ts +2 -3
  18. package/src/operations/extract.ts +13 -14
  19. package/src/operations/filter.ts +5 -6
  20. package/src/operations/label.ts +7 -8
  21. package/src/operations/rewrite.ts +3 -4
  22. package/src/operations/summarize.ts +4 -5
  23. package/src/operations/text.ts +4 -5
  24. package/src/utils.ts +1 -2
  25. package/src/zai.ts +4 -4
  26. package/dist/esm/adapters/adapter.js +0 -5
  27. package/dist/esm/adapters/botpress-table.js +0 -194
  28. package/dist/esm/adapters/memory.js +0 -15
  29. package/dist/esm/index.js +0 -11
  30. package/dist/esm/models.js +0 -390
  31. package/dist/esm/operations/check.js +0 -149
  32. package/dist/esm/operations/constants.js +0 -6
  33. package/dist/esm/operations/errors.js +0 -18
  34. package/dist/esm/operations/extract.js +0 -217
  35. package/dist/esm/operations/filter.js +0 -189
  36. package/dist/esm/operations/label.js +0 -246
  37. package/dist/esm/operations/rewrite.js +0 -113
  38. package/dist/esm/operations/summarize.js +0 -134
  39. package/dist/esm/operations/text.js +0 -48
  40. package/dist/esm/utils.js +0 -51
  41. package/dist/esm/zai.js +0 -161
  42. /package/dist/{csj → node}/adapters/adapter.js +0 -0
  43. /package/dist/{csj → node}/adapters/memory.js +0 -0
  44. /package/dist/{csj → node}/index.js +0 -0
  45. /package/dist/{csj → node}/models.js +0 -0
  46. /package/dist/{csj → node}/operations/constants.js +0 -0
  47. /package/dist/{csj → node}/operations/errors.js +0 -0
@@ -1,149 +0,0 @@
1
- import sdk from "@botpress/sdk";
2
- const { z } = sdk;
3
- import { fastHash, stringify, takeUntilTokens } from "../utils";
4
- import { Zai } from "../zai";
5
- import { PROMPT_INPUT_BUFFER } from "./constants";
6
- const Example = z.object({
7
- input: z.any(),
8
- check: z.boolean(),
9
- reason: z.string().optional()
10
- });
11
- const Options = z.object({
12
- examples: z.array(Example).describe("Examples to check the condition against").default([])
13
- });
14
- const TRUE = "\u25A0TRUE\u25A0";
15
- const FALSE = "\u25A0FALSE\u25A0";
16
- const END = "\u25A0END\u25A0";
17
- Zai.prototype.check = async function(input, condition, _options) {
18
- var _a;
19
- const options = Options.parse(_options != null ? _options : {});
20
- const tokenizer = await this.getTokenizer();
21
- const PROMPT_COMPONENT = Math.max(this.Model.input.maxTokens - PROMPT_INPUT_BUFFER, 100);
22
- const taskId = this.taskId;
23
- const taskType = "zai.check";
24
- const PROMPT_TOKENS = {
25
- INPUT: Math.floor(0.5 * PROMPT_COMPONENT),
26
- CONDITION: Math.floor(0.2 * PROMPT_COMPONENT)
27
- };
28
- const inputAsString = tokenizer.truncate(stringify(input), PROMPT_TOKENS.INPUT);
29
- condition = tokenizer.truncate(condition, PROMPT_TOKENS.CONDITION);
30
- const EXAMPLES_TOKENS = PROMPT_COMPONENT - tokenizer.count(inputAsString) - tokenizer.count(condition);
31
- const Key = fastHash(
32
- JSON.stringify({
33
- taskType,
34
- taskId,
35
- input: inputAsString,
36
- condition
37
- })
38
- );
39
- const examples = taskId ? await this.adapter.getExamples({
40
- input: inputAsString,
41
- taskType,
42
- taskId
43
- }) : [];
44
- const exactMatch = examples.find((x) => x.key === Key);
45
- if (exactMatch) {
46
- return exactMatch.output;
47
- }
48
- const defaultExamples = [
49
- { input: "50 Cent", check: true, reason: "50 Cent is widely recognized as a public personality." },
50
- {
51
- input: ["apple", "banana", "carrot", "house"],
52
- check: false,
53
- reason: "The list contains a house, which is not a fruit. Also, the list contains a carrot, which is a vegetable."
54
- }
55
- ];
56
- const userExamples = [
57
- ...examples.map((e) => ({ input: e.input, check: e.output, reason: e.explanation })),
58
- ...options.examples
59
- ];
60
- let exampleId = 1;
61
- const formatInput = (input2, condition2) => {
62
- const header = userExamples.length ? `Expert Example #${exampleId++}` : `Example of condition: "${condition2}"`;
63
- return `
64
- ${header}
65
- <|start_input|>
66
- ${input2.trim()}
67
- <|end_input|>
68
- `.trim();
69
- };
70
- const formatOutput = (answer2, justification) => {
71
- return `
72
- Analysis: ${justification}
73
- Final Answer: ${answer2 ? TRUE : FALSE}
74
- ${END}
75
- `.trim();
76
- };
77
- const formatExample = (example) => {
78
- var _a2, _b;
79
- return [
80
- { type: "text", content: formatInput(stringify((_a2 = example.input) != null ? _a2 : null), condition), role: "user" },
81
- {
82
- type: "text",
83
- content: formatOutput(example.check, (_b = example.reason) != null ? _b : ""),
84
- role: "assistant"
85
- }
86
- ];
87
- };
88
- const allExamples = takeUntilTokens(
89
- userExamples.length ? userExamples : defaultExamples,
90
- EXAMPLES_TOKENS,
91
- (el) => {
92
- var _a2;
93
- return tokenizer.count(stringify(el.input)) + tokenizer.count((_a2 = el.reason) != null ? _a2 : "");
94
- }
95
- ).map(formatExample).flat();
96
- const specialInstructions = userExamples.length ? `
97
- - You have been provided with examples from previous experts. Make sure to read them carefully before making your decision.
98
- - Make sure to refer to the examples provided by the experts to justify your decision (when applicable).
99
- - When in doubt, ground your decision on the examples provided by the experts instead of your own intuition.
100
- - When no example is similar to the input, make sure to provide a clear justification for your decision while inferring the decision-making process from the examples provided by the experts.
101
- `.trim() : "";
102
- const output = await this.callModel({
103
- systemPrompt: `
104
- Check if the following condition is true or false for the given input. Before answering, make sure to read the input and the condition carefully.
105
- Justify your answer, then answer with either ${TRUE} or ${FALSE} at the very end, then add ${END} to finish the response.
106
- IMPORTANT: Make sure to answer with either ${TRUE} or ${FALSE} at the end of your response, but NOT both.
107
- ---
108
- Expert Examples (#1 to #${exampleId - 1}):
109
- ${specialInstructions}
110
- `.trim(),
111
- stopSequences: [END],
112
- messages: [
113
- ...allExamples,
114
- {
115
- type: "text",
116
- content: `
117
- Considering the below input and above examples, is the following condition true or false?
118
- ${formatInput(inputAsString, condition)}
119
- In your "Analysis", please refer to the Expert Examples # to justify your decision.`.trim(),
120
- role: "user"
121
- }
122
- ]
123
- });
124
- const answer = (_a = output.choices[0]) == null ? void 0 : _a.content;
125
- const hasTrue = answer.includes(TRUE);
126
- const hasFalse = answer.includes(FALSE);
127
- if (!hasTrue && !hasFalse) {
128
- throw new Error(`The model did not return a valid answer. The response was: ${answer}`);
129
- }
130
- let finalAnswer;
131
- if (hasTrue && hasFalse) {
132
- finalAnswer = answer.lastIndexOf(TRUE) > answer.lastIndexOf(FALSE);
133
- } else {
134
- finalAnswer = hasTrue;
135
- }
136
- if (taskId) {
137
- await this.adapter.saveExample({
138
- key: Key,
139
- taskType,
140
- taskId,
141
- input: inputAsString,
142
- instructions: condition,
143
- metadata: output.metadata,
144
- output: finalAnswer,
145
- explanation: answer.replace(TRUE, "").replace(FALSE, "").replace(END, "").replace("Final Answer:", "").trim()
146
- });
147
- }
148
- return finalAnswer;
149
- };
@@ -1,6 +0,0 @@
1
- const PROMPT_INPUT_BUFFER = 1048;
2
- const PROMPT_OUTPUT_BUFFER = 512;
3
- export {
4
- PROMPT_INPUT_BUFFER,
5
- PROMPT_OUTPUT_BUFFER
6
- };
@@ -1,18 +0,0 @@
1
- class JsonParsingError extends Error {
2
- constructor(json, error) {
3
- const message = `Error parsing JSON:
4
-
5
- ---JSON---
6
- ${json}
7
-
8
- ---Error---
9
-
10
- ${error}`;
11
- super(message);
12
- this.json = json;
13
- this.error = error;
14
- }
15
- }
16
- export {
17
- JsonParsingError
18
- };
@@ -1,217 +0,0 @@
1
- import sdk from "@botpress/sdk";
2
- const { z } = sdk;
3
- import JSON5 from "json5";
4
- import { jsonrepair } from "jsonrepair";
5
- import _ from "lodash";
6
- import { fastHash, stringify, takeUntilTokens } from "../utils";
7
- import { Zai } from "../zai";
8
- import { PROMPT_INPUT_BUFFER } from "./constants";
9
- import { JsonParsingError } from "./errors";
10
- const Options = z.object({
11
- instructions: z.string().optional().describe("Instructions to guide the user on how to extract the data"),
12
- chunkLength: z.number().min(100).max(1e5).optional().describe("The maximum number of tokens per chunk").default(16e3)
13
- });
14
- const START = "\u25A0json_start\u25A0";
15
- const END = "\u25A0json_end\u25A0";
16
- const NO_MORE = "\u25A0NO_MORE_ELEMENT\u25A0";
17
- Zai.prototype.extract = async function(input, schema, _options) {
18
- var _a, _b, _c;
19
- const options = Options.parse(_options != null ? _options : {});
20
- const tokenizer = await this.getTokenizer();
21
- const taskId = this.taskId;
22
- const taskType = "zai.extract";
23
- const PROMPT_COMPONENT = Math.max(this.Model.input.maxTokens - PROMPT_INPUT_BUFFER, 100);
24
- let isArrayOfObjects = false;
25
- const originalSchema = schema;
26
- if (schema instanceof sdk.ZodObject) {
27
- } else if (schema instanceof sdk.ZodArray) {
28
- if (schema._def.type instanceof sdk.ZodObject) {
29
- isArrayOfObjects = true;
30
- schema = schema._def.type;
31
- } else {
32
- throw new Error("Schema must be a ZodObject or a ZodArray<ZodObject>");
33
- }
34
- } else {
35
- throw new Error("Schema must be either a ZuiObject or a ZuiArray<ZuiObject>");
36
- }
37
- const schemaTypescript = schema.toTypescript({ declaration: false });
38
- const schemaLength = tokenizer.count(schemaTypescript);
39
- options.chunkLength = Math.min(options.chunkLength, this.Model.input.maxTokens - PROMPT_INPUT_BUFFER - schemaLength);
40
- const keys = Object.keys(schema.shape);
41
- let inputAsString = stringify(input);
42
- if (tokenizer.count(inputAsString) > options.chunkLength) {
43
- if (isArrayOfObjects) {
44
- const tokens = tokenizer.split(inputAsString);
45
- const chunks = _.chunk(tokens, options.chunkLength).map((x) => x.join(""));
46
- const all = await Promise.all(chunks.map((chunk) => this.extract(chunk, originalSchema)));
47
- return all.flat();
48
- } else {
49
- inputAsString = tokenizer.truncate(stringify(input), options.chunkLength);
50
- }
51
- }
52
- const instructions = [];
53
- if (options.instructions) {
54
- instructions.push(options.instructions);
55
- }
56
- const shape = `{ ${keys.map((key) => `"${key}": ...`).join(", ")} }`;
57
- const abbv = "{ ... }";
58
- if (isArrayOfObjects) {
59
- instructions.push("You may have multiple elements, or zero elements in the input.");
60
- instructions.push("You must extract each element separately.");
61
- instructions.push(`Each element must be a JSON object with exactly the format: ${START}${shape}${END}`);
62
- instructions.push(`When you are done extracting all elements, type "${NO_MORE}" to finish.`);
63
- instructions.push(`For example, if you have zero elements, the output should look like this: ${NO_MORE}`);
64
- instructions.push(
65
- `For example, if you have two elements, the output should look like this: ${START}${abbv}${END}${START}${abbv}${END}${NO_MORE}`
66
- );
67
- } else {
68
- instructions.push("You may have exactly one element in the input.");
69
- instructions.push(`The element must be a JSON object with exactly the format: ${START}${shape}${END}`);
70
- }
71
- const EXAMPLES_TOKENS = PROMPT_COMPONENT - tokenizer.count(inputAsString) - tokenizer.count(instructions.join("\n"));
72
- const Key = fastHash(
73
- JSON.stringify({
74
- taskType,
75
- taskId,
76
- input: inputAsString,
77
- instructions: options.instructions
78
- })
79
- );
80
- const examples = taskId ? await this.adapter.getExamples({
81
- input: inputAsString,
82
- taskType,
83
- taskId
84
- }) : [];
85
- const exactMatch = examples.find((x) => x.key === Key);
86
- if (exactMatch) {
87
- return exactMatch.output;
88
- }
89
- const defaultExample = isArrayOfObjects ? {
90
- input: `The story goes as follow.
91
- Once upon a time, there was a person named Alice who was 30 years old.
92
- Then, there was a person named Bob who was 25 years old.
93
- The end.`,
94
- schema: "Array<{ name: string, age: number }>",
95
- instructions: "Extract all people",
96
- extracted: [
97
- {
98
- name: "Alice",
99
- age: 30
100
- },
101
- {
102
- name: "Bob",
103
- age: 25
104
- }
105
- ]
106
- } : {
107
- input: `The story goes as follow.
108
- Once upon a time, there was a person named Alice who was 30 years old.
109
- The end.`,
110
- schema: "{ name: string, age: number }",
111
- instructions: "Extract the person",
112
- extracted: { name: "Alice", age: 30 }
113
- };
114
- const userExamples = examples.map((e) => ({
115
- input: e.input,
116
- extracted: e.output,
117
- schema: schemaTypescript,
118
- instructions: options.instructions
119
- }));
120
- let exampleId = 1;
121
- const formatInput = (input2, schema2, instructions2) => {
122
- const header = userExamples.length ? `Expert Example #${exampleId++}` : "Here's an example to help you understand the format:";
123
- return `
124
- ${header}
125
-
126
- <|start_schema|>
127
- ${schema2}
128
- <|end_schema|>
129
-
130
- <|start_instructions|>
131
- ${instructions2 != null ? instructions2 : "No specific instructions, just follow the schema above."}
132
- <|end_instructions|>
133
-
134
- <|start_input|>
135
- ${input2.trim()}
136
- <|end_input|>
137
- `.trim();
138
- };
139
- const formatOutput = (extracted) => {
140
- extracted = _.isArray(extracted) ? extracted : [extracted];
141
- return extracted.map(
142
- (x) => `
143
- ${START}
144
- ${JSON.stringify(x, null, 2)}
145
- ${END}`.trim()
146
- ).join("\n") + NO_MORE;
147
- };
148
- const formatExample = (example) => {
149
- var _a2;
150
- return [
151
- {
152
- type: "text",
153
- content: formatInput(stringify((_a2 = example.input) != null ? _a2 : null), example.schema, example.instructions),
154
- role: "user"
155
- },
156
- {
157
- type: "text",
158
- content: formatOutput(example.extracted),
159
- role: "assistant"
160
- }
161
- ];
162
- };
163
- const allExamples = takeUntilTokens(
164
- userExamples.length ? userExamples : [defaultExample],
165
- EXAMPLES_TOKENS,
166
- (el) => tokenizer.count(stringify(el.input)) + tokenizer.count(stringify(el.extracted))
167
- ).map(formatExample).flat();
168
- const output = await this.callModel({
169
- systemPrompt: `
170
- Extract the following information from the input:
171
- ${schemaTypescript}
172
- ====
173
-
174
- ${instructions.map((x) => `\u2022 ${x}`).join("\n")}
175
- `.trim(),
176
- stopSequences: [isArrayOfObjects ? NO_MORE : END],
177
- messages: [
178
- ...allExamples,
179
- {
180
- role: "user",
181
- type: "text",
182
- content: formatInput(inputAsString, schemaTypescript, (_a = options.instructions) != null ? _a : "")
183
- }
184
- ]
185
- });
186
- const answer = (_b = output.choices[0]) == null ? void 0 : _b.content;
187
- const elements = answer.split(START).filter((x) => x.trim().length > 0).map((x) => {
188
- try {
189
- const json = x.slice(0, x.indexOf(END)).trim();
190
- const repairedJson = jsonrepair(json);
191
- const parsedJson = JSON5.parse(repairedJson);
192
- return schema.parse(parsedJson);
193
- } catch (error) {
194
- throw new JsonParsingError(x, error instanceof Error ? error : new Error("Unknown error"));
195
- }
196
- }).filter((x) => x !== null);
197
- let final;
198
- if (isArrayOfObjects) {
199
- final = elements;
200
- } else if (elements.length === 0) {
201
- final = schema.parse({});
202
- } else {
203
- final = elements[0];
204
- }
205
- if (taskId) {
206
- await this.adapter.saveExample({
207
- key: Key,
208
- taskId: `zai/${taskId}`,
209
- taskType,
210
- instructions: (_c = options.instructions) != null ? _c : "No specific instructions",
211
- input: inputAsString,
212
- output: final,
213
- metadata: output.metadata
214
- });
215
- }
216
- return final;
217
- };
@@ -1,189 +0,0 @@
1
- import sdk from "@botpress/sdk";
2
- const { z } = sdk;
3
- import _ from "lodash";
4
- import { fastHash, stringify, takeUntilTokens } from "../utils";
5
- import { Zai } from "../zai";
6
- import { PROMPT_INPUT_BUFFER, PROMPT_OUTPUT_BUFFER } from "./constants";
7
- const Example = z.object({
8
- input: z.any(),
9
- filter: z.boolean(),
10
- reason: z.string().optional()
11
- });
12
- const Options = z.object({
13
- tokensPerItem: z.number().min(1).max(1e5).optional().describe("The maximum number of tokens per item").default(250),
14
- examples: z.array(Example).describe("Examples to filter the condition against").default([])
15
- });
16
- const END = "\u25A0END\u25A0";
17
- Zai.prototype.filter = async function(input, condition, _options) {
18
- const options = Options.parse(_options != null ? _options : {});
19
- const tokenizer = await this.getTokenizer();
20
- const taskId = this.taskId;
21
- const taskType = "zai.filter";
22
- const MAX_ITEMS_PER_CHUNK = 50;
23
- const TOKENS_TOTAL_MAX = this.Model.input.maxTokens - PROMPT_INPUT_BUFFER - PROMPT_OUTPUT_BUFFER;
24
- const TOKENS_EXAMPLES_MAX = Math.floor(Math.max(250, TOKENS_TOTAL_MAX * 0.5));
25
- const TOKENS_CONDITION_MAX = _.clamp(TOKENS_TOTAL_MAX * 0.25, 250, tokenizer.count(condition));
26
- const TOKENS_INPUT_ARRAY_MAX = TOKENS_TOTAL_MAX - TOKENS_EXAMPLES_MAX - TOKENS_CONDITION_MAX;
27
- condition = tokenizer.truncate(condition, TOKENS_CONDITION_MAX);
28
- let chunks = [];
29
- let currentChunk = [];
30
- let currentChunkTokens = 0;
31
- for (const element of input) {
32
- const elementAsString = tokenizer.truncate(stringify(element, false), options.tokensPerItem);
33
- const elementTokens = tokenizer.count(elementAsString);
34
- if (currentChunkTokens + elementTokens > TOKENS_INPUT_ARRAY_MAX || currentChunk.length >= MAX_ITEMS_PER_CHUNK) {
35
- chunks.push(currentChunk);
36
- currentChunk = [];
37
- currentChunkTokens = 0;
38
- }
39
- currentChunk.push(element);
40
- currentChunkTokens += elementTokens;
41
- }
42
- if (currentChunk.length > 0) {
43
- chunks.push(currentChunk);
44
- }
45
- chunks = chunks.filter((x) => x.length > 0);
46
- const formatInput = (input2, condition2) => {
47
- return `
48
- Condition to check:
49
- ${condition2}
50
-
51
- Items (from \u25A00 to \u25A0${input2.length - 1})
52
- ==============================
53
- ${input2.map((x, idx) => {
54
- var _a;
55
- return `\u25A0${idx} = ${stringify((_a = x.input) != null ? _a : null, false)}`;
56
- }).join("\n")}
57
- `.trim();
58
- };
59
- const formatExamples = (examples) => {
60
- return `
61
- ${examples.map((x, idx) => `\u25A0${idx}:${!!x.filter ? "true" : "false"}`).join("")}
62
- ${END}
63
- ====
64
- Here's the reasoning behind each example:
65
- ${examples.map((x, idx) => {
66
- var _a;
67
- return `\u25A0${idx}:${!!x.filter ? "true" : "false"}:${(_a = x.reason) != null ? _a : "No reason provided"}`;
68
- }).join("\n")}
69
- `.trim();
70
- };
71
- const genericExamples = [
72
- {
73
- input: "apple",
74
- filter: true,
75
- reason: "Apples are fruits"
76
- },
77
- {
78
- input: "Apple Inc.",
79
- filter: false,
80
- reason: "Apple Inc. is a company, not a fruit"
81
- },
82
- {
83
- input: "banana",
84
- filter: true,
85
- reason: "Bananas are fruits"
86
- },
87
- {
88
- input: "potato",
89
- filter: false,
90
- reason: "Potatoes are vegetables"
91
- }
92
- ];
93
- const genericExamplesMessages = [
94
- {
95
- type: "text",
96
- content: formatInput(genericExamples, "is a fruit"),
97
- role: "user"
98
- },
99
- {
100
- type: "text",
101
- content: formatExamples(genericExamples),
102
- role: "assistant"
103
- }
104
- ];
105
- const filterChunk = async (chunk) => {
106
- var _a, _b;
107
- const examples = taskId ? await this.adapter.getExamples({
108
- // The Table API can't search for a huge input string
109
- input: JSON.stringify(chunk).slice(0, 1e3),
110
- taskType,
111
- taskId
112
- }).then(
113
- (x) => x.map((y) => ({ filter: y.output, input: y.input, reason: y.explanation }))
114
- ) : [];
115
- const allExamples = takeUntilTokens(
116
- [...examples, ...(_a = options.examples) != null ? _a : []],
117
- TOKENS_EXAMPLES_MAX,
118
- (el) => tokenizer.count(stringify(el.input))
119
- );
120
- const exampleMessages = [
121
- {
122
- type: "text",
123
- content: formatInput(allExamples, condition),
124
- role: "user"
125
- },
126
- {
127
- type: "text",
128
- content: formatExamples(allExamples),
129
- role: "assistant"
130
- }
131
- ];
132
- const output = await this.callModel({
133
- systemPrompt: `
134
- You are given a list of items. Your task is to filter out the items that meet the condition below.
135
- You need to return the full list of items with the format:
136
- \u25A0x:true\u25A0y:false\u25A0z:true (where x, y, z are the indices of the items in the list)
137
- You need to start with "\u25A00" and go up to the last index "\u25A0${chunk.length - 1}".
138
- If an item meets the condition, you should return ":true", otherwise ":false".
139
-
140
- IMPORTANT: Make sure to read the condition and the examples carefully before making your decision.
141
- The condition is: "${condition}"
142
- `.trim(),
143
- stopSequences: [END],
144
- messages: [
145
- ...exampleMessages.length ? exampleMessages : genericExamplesMessages,
146
- {
147
- type: "text",
148
- content: formatInput(
149
- chunk.map((x) => ({ input: x })),
150
- condition
151
- ),
152
- role: "user"
153
- }
154
- ]
155
- });
156
- const answer = (_b = output.choices[0]) == null ? void 0 : _b.content;
157
- const indices = answer.trim().split("\u25A0").filter((x) => x.length > 0).map((x) => {
158
- var _a2;
159
- const [idx, filter] = x.split(":");
160
- return { idx: parseInt((_a2 = idx == null ? void 0 : idx.trim()) != null ? _a2 : ""), filter: (filter == null ? void 0 : filter.toLowerCase().trim()) === "true" };
161
- });
162
- const partial = chunk.filter((_2, idx) => {
163
- var _a2, _b2;
164
- return (_b2 = (_a2 = indices.find((x) => x.idx === idx)) == null ? void 0 : _a2.filter) != null ? _b2 : false;
165
- });
166
- if (taskId) {
167
- const key = fastHash(
168
- stringify({
169
- taskId,
170
- taskType,
171
- input: JSON.stringify(chunk),
172
- condition
173
- })
174
- );
175
- await this.adapter.saveExample({
176
- key,
177
- taskType,
178
- taskId,
179
- input: JSON.stringify(chunk),
180
- output: partial,
181
- instructions: condition,
182
- metadata: output.metadata
183
- });
184
- }
185
- return partial;
186
- };
187
- const filteredChunks = await Promise.all(chunks.map(filterChunk));
188
- return filteredChunks.flat();
189
- };