@try-works/extension-laya 0.0.0-stage → 1.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 +38 -2
- package/lib/index.d.ts +18 -0
- package/lib/index.js +172 -0
- package/lib/index.js.map +1 -0
- package/lib/pure.d.ts +35 -0
- package/lib/pure.js +71 -0
- package/lib/pure.js.map +1 -0
- package/models.lock.json +63 -0
- package/package.json +39 -4
- package/schema/decision-choose.input.json +22 -0
- package/schema/decision-choose.output.json +20 -0
- package/schema/decision-score.input.json +18 -0
- package/schema/decision-score.output.json +18 -0
- package/schema/decision-test.input.json +10 -0
- package/schema/decision-test.output.json +18 -0
- package/tool-mode.extension.json +87 -0
- package/vendor/LICENSE.laya-ts +176 -0
- package/vendor/laya-ts/agent.d.ts +216 -0
- package/vendor/laya-ts/agent.js +631 -0
- package/vendor/laya-ts/common.d.ts +167 -0
- package/vendor/laya-ts/common.js +478 -0
- package/vendor/laya-ts/dx.d.ts +17 -0
- package/vendor/laya-ts/dx.js +46 -0
- package/vendor/laya-ts/email.d.ts +2 -0
- package/vendor/laya-ts/email.js +184 -0
- package/vendor/laya-ts/hooks.d.ts +134 -0
- package/vendor/laya-ts/hooks.js +379 -0
- package/vendor/laya-ts/index.d.ts +22 -0
- package/vendor/laya-ts/index.js +13 -0
- package/vendor/laya-ts/lang.d.ts +24 -0
- package/vendor/laya-ts/lang.js +590 -0
- package/vendor/laya-ts/presets.d.ts +5 -0
- package/vendor/laya-ts/presets.js +175 -0
- package/vendor/laya-ts/providers.d.ts +67 -0
- package/vendor/laya-ts/providers.js +668 -0
- package/vendor/laya-ts/router.d.ts +186 -0
- package/vendor/laya-ts/router.js +757 -0
- package/vendor/laya-ts/shortlist.d.ts +65 -0
- package/vendor/laya-ts/shortlist.js +407 -0
- package/vendor/laya-ts/structured.d.ts +89 -0
- package/vendor/laya-ts/structured.js +256 -0
- package/vendor/laya-ts/tokenizer.d.ts +66 -0
- package/vendor/laya-ts/tokenizer.js +482 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { QuestionDef, SystemOneResult } from "./agent.js";
|
|
2
|
+
export declare const DEFAULT_SHORTLIST_K = 20;
|
|
3
|
+
export declare const DEFAULT_TOURNAMENT_GROUP = 16;
|
|
4
|
+
export declare const DEFAULT_SHORTLIST_MAXSIZE = 4096;
|
|
5
|
+
export type EmbedFn = (texts: string[]) => Promise<number[][]> | number[][];
|
|
6
|
+
export interface ShortlistMeta {
|
|
7
|
+
labels: string[];
|
|
8
|
+
scores: number[] | null;
|
|
9
|
+
k: number;
|
|
10
|
+
n: number;
|
|
11
|
+
passthrough: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface TournamentMeta {
|
|
14
|
+
labels: string[];
|
|
15
|
+
n: number;
|
|
16
|
+
rounds: number;
|
|
17
|
+
}
|
|
18
|
+
export interface CacheInfo {
|
|
19
|
+
size: number;
|
|
20
|
+
maxsize: number;
|
|
21
|
+
hits: number;
|
|
22
|
+
misses: number;
|
|
23
|
+
}
|
|
24
|
+
export interface CachedEmbedFn {
|
|
25
|
+
(texts: string[]): Promise<number[][]>;
|
|
26
|
+
cacheInfo(): CacheInfo;
|
|
27
|
+
cache_info(): CacheInfo;
|
|
28
|
+
cacheClear(): void;
|
|
29
|
+
cache_clear(): void;
|
|
30
|
+
}
|
|
31
|
+
/** Return the top-k choice labels for state. Skips embed_fn when k >= n. */
|
|
32
|
+
export declare function shortlistChoice(state: unknown, criteria: unknown, embedFn: EmbedFn, k?: number, instructions?: unknown): Promise<string[]>;
|
|
33
|
+
/** Shortlist each choice question, then call predict/systemOne once. */
|
|
34
|
+
export declare function predictShortlist(agent: unknown, state: unknown, questions: Record<string, QuestionDef>, embedFn?: EmbedFn | null, k?: number, predictKwargs?: Record<string, unknown>): Promise<SystemOneResult & {
|
|
35
|
+
shortlist: Record<string, ShortlistMeta>;
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* Reduce large choices through balanced elimination rounds, then predict all questions.
|
|
39
|
+
* Each round batches every group's question in one call. Metadata lists the finalists;
|
|
40
|
+
* probabilities, confidence, usage and other result fields come from the final call only.
|
|
41
|
+
*/
|
|
42
|
+
export declare function predictTournament(agent: unknown, state: unknown, questions: Record<string, QuestionDef>, groupSize?: number, predictKwargs?: Record<string, unknown>): Promise<SystemOneResult & {
|
|
43
|
+
tournament: Record<string, TournamentMeta>;
|
|
44
|
+
}>;
|
|
45
|
+
/** Mean-pool the agent's provider encoder. Throws honestly without encoder access. */
|
|
46
|
+
export declare function embedFnFromAgent(agent: unknown, maxLength?: number, batchSize?: number): EmbedFn;
|
|
47
|
+
/**
|
|
48
|
+
* Wrap `embedFn` with an LRU cache keyed by text.
|
|
49
|
+
*
|
|
50
|
+
* Shortlisting embeds the query plus every option on every call. When the option
|
|
51
|
+
* set is fixed -- a label list, an intent taxonomy -- those rows never change
|
|
52
|
+
* between requests and are re-embedded every time. Wrapping the embedder once
|
|
53
|
+
* leaves the first call unchanged and reduces each repeat to embedding the new
|
|
54
|
+
* query alone.
|
|
55
|
+
*
|
|
56
|
+
* A cold cache costs the same number of embedder calls as the unwrapped function:
|
|
57
|
+
* the misses are deduplicated and embedded in one call. Nothing is cached when
|
|
58
|
+
* the embedder throws or returns a bad shape, so a transient failure cannot
|
|
59
|
+
* poison the cache.
|
|
60
|
+
*
|
|
61
|
+
* @param embedFn The underlying embedding function
|
|
62
|
+
* @param maxsize Maximum number of distinct text rows to cache (default: 4096)
|
|
63
|
+
*/
|
|
64
|
+
export declare function cachedEmbedFn(embedFn: EmbedFn, maxsize?: number): CachedEmbedFn;
|
|
65
|
+
export declare const cached: typeof cachedEmbedFn;
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { maxOf, renderOptions, serializeState } from "./common.js";
|
|
2
|
+
export const DEFAULT_SHORTLIST_K = 20;
|
|
3
|
+
export const DEFAULT_TOURNAMENT_GROUP = 16;
|
|
4
|
+
export const DEFAULT_SHORTLIST_MAXSIZE = 4096;
|
|
5
|
+
function checkK(k) {
|
|
6
|
+
if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
|
|
7
|
+
throw new Error(`k must be a positive integer, got ${JSON.stringify(k)}`);
|
|
8
|
+
}
|
|
9
|
+
return k;
|
|
10
|
+
}
|
|
11
|
+
function criteriaItems(criteria) {
|
|
12
|
+
let items;
|
|
13
|
+
if (Array.isArray(criteria)) {
|
|
14
|
+
items = criteria.map((item) => [String(item), null]);
|
|
15
|
+
}
|
|
16
|
+
else if (typeof criteria === "object" && criteria !== null) {
|
|
17
|
+
items = Object.entries(criteria);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
throw new TypeError(`choice criteria must be a dict or list, got ${Array.isArray(criteria) ? "list" : criteria === null ? "NoneType" : typeof criteria}`);
|
|
21
|
+
}
|
|
22
|
+
if (items.length === 0)
|
|
23
|
+
throw new Error("choice criteria must contain at least one option");
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
for (const [key] of items) {
|
|
26
|
+
if (seen.has(key))
|
|
27
|
+
throw new Error(`choice criteria label ${JSON.stringify(key)} is duplicated`);
|
|
28
|
+
seen.add(key);
|
|
29
|
+
}
|
|
30
|
+
return items;
|
|
31
|
+
}
|
|
32
|
+
function optionTexts(items) {
|
|
33
|
+
const crit = Object.fromEntries(items);
|
|
34
|
+
const rendered = renderOptions({ t: "choice", ins: "", crit });
|
|
35
|
+
if (rendered.length !== items.length)
|
|
36
|
+
throw new Error("could not render every choice option");
|
|
37
|
+
return rendered.map((p) => (typeof p === "string" ? p : String(p)));
|
|
38
|
+
}
|
|
39
|
+
function queryText(state, instructions) {
|
|
40
|
+
const body = serializeState(state);
|
|
41
|
+
if (instructions === null || instructions === undefined || instructions === "")
|
|
42
|
+
return body;
|
|
43
|
+
if (typeof instructions !== "string")
|
|
44
|
+
return `${JSON.stringify(instructions)}\n${body}`;
|
|
45
|
+
return `${instructions}\n${body}`;
|
|
46
|
+
}
|
|
47
|
+
function clean(v) {
|
|
48
|
+
return typeof v !== "number" || !Number.isFinite(v) ? 0 : v;
|
|
49
|
+
}
|
|
50
|
+
async function embeddings(embedFn, texts) {
|
|
51
|
+
if (typeof embedFn !== "function")
|
|
52
|
+
throw new TypeError("embed_fn must be callable");
|
|
53
|
+
const raw = await embedFn([...texts]);
|
|
54
|
+
const arr = raw;
|
|
55
|
+
if (!Array.isArray(arr) || arr.length !== texts.length) {
|
|
56
|
+
throw new Error(`embed_fn must return an array of shape (${texts.length}, dim), got ${Array.isArray(arr) ? `(${arr.length}, ?)` : typeof arr}`);
|
|
57
|
+
}
|
|
58
|
+
const rows = arr.map((row) => {
|
|
59
|
+
if (!Array.isArray(row) || row.length < 1) {
|
|
60
|
+
throw new Error(`embed_fn must return an array of shape (${texts.length}, dim), got row ${JSON.stringify(row)?.slice(0, 60)}`);
|
|
61
|
+
}
|
|
62
|
+
return row.map((v) => clean(Number(v)));
|
|
63
|
+
});
|
|
64
|
+
return rows;
|
|
65
|
+
}
|
|
66
|
+
function cosine(query, docs) {
|
|
67
|
+
const qn = Math.sqrt(query.reduce((a, v) => a + v * v, 0));
|
|
68
|
+
if (qn === 0 || docs.length === 0)
|
|
69
|
+
return docs.map(() => 0);
|
|
70
|
+
return docs.map((d) => {
|
|
71
|
+
const dn = Math.sqrt(d.reduce((a, v) => a + v * v, 0));
|
|
72
|
+
if (dn === 0)
|
|
73
|
+
return 0;
|
|
74
|
+
const dot = d.reduce((a, v, i) => a + v * (query[i] ?? 0), 0);
|
|
75
|
+
return Math.min(1, Math.max(-1, dot / (dn * qn)));
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async function rank(state, criteria, embedFn, k, instructions) {
|
|
79
|
+
const checked = checkK(k);
|
|
80
|
+
const items = criteriaItems(criteria);
|
|
81
|
+
const n = items.length;
|
|
82
|
+
const keys = items.map(([key]) => key);
|
|
83
|
+
if (checked >= n)
|
|
84
|
+
return { labels: [...keys], scores: null, passthrough: true, n };
|
|
85
|
+
const q = queryText(state, instructions);
|
|
86
|
+
const matrix = await embeddings(embedFn, [q, ...optionTexts(items)]);
|
|
87
|
+
const sims = cosine(matrix[0], matrix.slice(1));
|
|
88
|
+
const order = sims
|
|
89
|
+
.map((s, i) => i)
|
|
90
|
+
.sort((a, b) => sims[b] - sims[a]);
|
|
91
|
+
const top = order.slice(0, checked);
|
|
92
|
+
return { labels: top.map((i) => keys[i]), scores: top.map((i) => sims[i]), passthrough: false, n };
|
|
93
|
+
}
|
|
94
|
+
function subsetCriteria(criteria, labels) {
|
|
95
|
+
if (Array.isArray(criteria))
|
|
96
|
+
return [...labels];
|
|
97
|
+
return Object.fromEntries(labels.map((l) => [l, criteria[l]]));
|
|
98
|
+
}
|
|
99
|
+
/** Return the top-k choice labels for state. Skips embed_fn when k >= n. */
|
|
100
|
+
export async function shortlistChoice(state, criteria, embedFn, k = DEFAULT_SHORTLIST_K, instructions) {
|
|
101
|
+
const { labels } = await rank(state, criteria, embedFn, k, instructions);
|
|
102
|
+
return labels;
|
|
103
|
+
}
|
|
104
|
+
/** Shortlist each choice question, then call predict/systemOne once. */
|
|
105
|
+
export async function predictShortlist(agent, state, questions, embedFn, k = DEFAULT_SHORTLIST_K, predictKwargs = {}) {
|
|
106
|
+
if (typeof questions !== "object" || questions === null || Array.isArray(questions)) {
|
|
107
|
+
throw new TypeError("questions must be a dict of question id -> definition");
|
|
108
|
+
}
|
|
109
|
+
const checked = checkK(k);
|
|
110
|
+
const needsEmbed = Object.values(questions).some((qdef) => typeof qdef === "object" && qdef !== null && !Array.isArray(qdef) &&
|
|
111
|
+
qdef["type"] === "choice" &&
|
|
112
|
+
"criteria" in qdef &&
|
|
113
|
+
Object.keys(qdef["criteria"] ?? {}).length > checked);
|
|
114
|
+
// Default bi-encoder is the agent itself; pass a dedicated embedFn only when it shortlists better.
|
|
115
|
+
const embed = embedFn ?? (needsEmbed ? embedFnFromAgent(agent) : null);
|
|
116
|
+
const reduced = {};
|
|
117
|
+
const meta = {};
|
|
118
|
+
for (const [qid, qdef] of Object.entries(questions)) {
|
|
119
|
+
if (typeof qdef !== "object" || qdef === null || Array.isArray(qdef) || qdef["type"] !== "choice") {
|
|
120
|
+
reduced[qid] = qdef;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (!("criteria" in qdef)) {
|
|
124
|
+
throw new Error(`question ${JSON.stringify(qid)} is a choice but has no criteria`);
|
|
125
|
+
}
|
|
126
|
+
const q = qdef;
|
|
127
|
+
const { labels, scores, passthrough, n } = await rank(state, q["criteria"], embed, checked, q["instructions"]);
|
|
128
|
+
meta[qid] = { labels: [...labels], scores, k: checked, n, passthrough };
|
|
129
|
+
if (passthrough) {
|
|
130
|
+
reduced[qid] = qdef;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
reduced[qid] = { ...q, criteria: subsetCriteria(q["criteria"], labels) };
|
|
134
|
+
}
|
|
135
|
+
const a = agent;
|
|
136
|
+
const fn = a?.["predict"] ?? a?.["systemOne"] ?? a?.["system_one"];
|
|
137
|
+
if (typeof fn !== "function")
|
|
138
|
+
throw new TypeError("agent must provide predict or system_one");
|
|
139
|
+
const extra = Object.keys(predictKwargs ?? {}).length ? [predictKwargs] : [];
|
|
140
|
+
const result = await fn.call(agent, state, reduced, ...extra);
|
|
141
|
+
if (typeof result !== "object" || result === null || Array.isArray(result)) {
|
|
142
|
+
throw new TypeError("predict/system_one must return a dict");
|
|
143
|
+
}
|
|
144
|
+
return { ...result, shortlist: meta };
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Reduce large choices through balanced elimination rounds, then predict all questions.
|
|
148
|
+
* Each round batches every group's question in one call. Metadata lists the finalists;
|
|
149
|
+
* probabilities, confidence, usage and other result fields come from the final call only.
|
|
150
|
+
*/
|
|
151
|
+
export async function predictTournament(agent, state, questions, groupSize = DEFAULT_TOURNAMENT_GROUP, predictKwargs = {}) {
|
|
152
|
+
if (typeof questions !== "object" || questions === null || Array.isArray(questions) ||
|
|
153
|
+
(Object.getPrototypeOf(questions) !== null && Object.getPrototypeOf(questions) !== Object.prototype)) {
|
|
154
|
+
throw new TypeError("questions must be a dict of question id -> definition");
|
|
155
|
+
}
|
|
156
|
+
if (!Number.isSafeInteger(groupSize) || groupSize < 2) {
|
|
157
|
+
throw new Error(`groupSize must be a safe integer >= 2, got ${JSON.stringify(groupSize)}`);
|
|
158
|
+
}
|
|
159
|
+
const meta = new Map();
|
|
160
|
+
for (const [qid, qdef] of Object.entries(questions)) {
|
|
161
|
+
if (typeof qdef !== "object" || qdef === null || Array.isArray(qdef) || qdef["type"] !== "choice")
|
|
162
|
+
continue;
|
|
163
|
+
if (!("criteria" in qdef)) {
|
|
164
|
+
throw new Error(`question ${JSON.stringify(qid)} is a choice but has no criteria`);
|
|
165
|
+
}
|
|
166
|
+
const criteria = qdef["criteria"];
|
|
167
|
+
if (Array.isArray(criteria)) {
|
|
168
|
+
for (const label of criteria) {
|
|
169
|
+
if (label === null || label === undefined || typeof label === "object") {
|
|
170
|
+
throw new Error(`question ${JSON.stringify(qid)}: choice labels must not be null, lists or dicts`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const labels = criteriaItems(criteria).map(([label]) => label);
|
|
175
|
+
meta.set(qid, { labels, n: labels.length, rounds: 0 });
|
|
176
|
+
}
|
|
177
|
+
const a = agent;
|
|
178
|
+
const fn = a?.["predict"] ?? a?.["systemOne"] ?? a?.["system_one"];
|
|
179
|
+
if (typeof fn !== "function")
|
|
180
|
+
throw new TypeError("agent must provide predict or system_one");
|
|
181
|
+
const extra = Object.keys(predictKwargs ?? {}).length ? [predictKwargs] : [];
|
|
182
|
+
const predict = async (current) => {
|
|
183
|
+
const result = await fn.call(agent, state, current, ...extra);
|
|
184
|
+
if (typeof result !== "object" || result === null || Array.isArray(result)) {
|
|
185
|
+
throw new TypeError("predict/system_one must return a dict");
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
};
|
|
189
|
+
const warned = new Set();
|
|
190
|
+
const cut = (qid, labels) => {
|
|
191
|
+
const original = questions[qid];
|
|
192
|
+
const narrowed = { ...original, criteria: subsetCriteria(original["criteria"], labels) };
|
|
193
|
+
if (Object.hasOwn(narrowed, "option_order")) {
|
|
194
|
+
delete narrowed["option_order"];
|
|
195
|
+
if (!warned.has(qid)) {
|
|
196
|
+
warned.add(qid);
|
|
197
|
+
console.warn(`laya.shortlist: question ${JSON.stringify(qid)}: 'option_order' was dropped because the label set was narrowed to ${labels.length}; the order no longer fits the kept options.`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return narrowed;
|
|
201
|
+
};
|
|
202
|
+
while (true) {
|
|
203
|
+
const groups = [];
|
|
204
|
+
for (const [qid, entry] of meta) {
|
|
205
|
+
const n = entry.labels.length;
|
|
206
|
+
const parts = Math.ceil(n / groupSize);
|
|
207
|
+
if (parts <= 1)
|
|
208
|
+
continue;
|
|
209
|
+
for (let i = 0; i < parts; i++) {
|
|
210
|
+
groups.push({ qid, labels: entry.labels.slice(Math.floor(i * n / parts), Math.floor((i + 1) * n / parts)) });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (groups.length === 0)
|
|
214
|
+
break;
|
|
215
|
+
const roundQuestions = Object.fromEntries(groups.map(({ qid, labels }, i) => [String(i), cut(qid, labels)]));
|
|
216
|
+
const result = await predict(roundQuestions);
|
|
217
|
+
const answers = result["answers"];
|
|
218
|
+
if (typeof answers !== "object" || answers === null || Array.isArray(answers)) {
|
|
219
|
+
throw new TypeError("tournament round must return an answers dict");
|
|
220
|
+
}
|
|
221
|
+
const winners = new Map();
|
|
222
|
+
for (const [i, { qid, labels }] of groups.entries()) {
|
|
223
|
+
const answer = Object.hasOwn(answers, String(i)) ? answers[String(i)] : undefined;
|
|
224
|
+
const choice = typeof answer === "object" && answer !== null && !Array.isArray(answer) && Object.hasOwn(answer, "choice")
|
|
225
|
+
? answer["choice"] : undefined;
|
|
226
|
+
if (typeof choice !== "string" || !labels.includes(choice)) {
|
|
227
|
+
throw new Error(`tournament group ${i} for question ${JSON.stringify(qid)} must return a choice from its criteria`);
|
|
228
|
+
}
|
|
229
|
+
const kept = winners.get(qid) ?? [];
|
|
230
|
+
kept.push(choice);
|
|
231
|
+
winners.set(qid, kept);
|
|
232
|
+
}
|
|
233
|
+
for (const [qid, labels] of winners) {
|
|
234
|
+
const entry = meta.get(qid);
|
|
235
|
+
entry.labels = labels;
|
|
236
|
+
entry.rounds++;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const finalQuestions = Object.fromEntries(Object.entries(questions).map(([qid, qdef]) => {
|
|
240
|
+
const entry = meta.get(qid);
|
|
241
|
+
return [qid, entry?.rounds ? cut(qid, entry.labels) : qdef];
|
|
242
|
+
}));
|
|
243
|
+
const result = await predict(finalQuestions);
|
|
244
|
+
return { ...result, tournament: Object.fromEntries(meta) };
|
|
245
|
+
}
|
|
246
|
+
/** Mean-pool the agent's provider encoder. Throws honestly without encoder access. */
|
|
247
|
+
export function embedFnFromAgent(agent, maxLength = 512, batchSize = 32) {
|
|
248
|
+
if (!Number.isInteger(maxLength) || maxLength < 1) {
|
|
249
|
+
throw new Error(`max_length must be a positive integer, got ${JSON.stringify(maxLength)}`);
|
|
250
|
+
}
|
|
251
|
+
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
252
|
+
throw new Error(`batch_size must be a positive integer, got ${JSON.stringify(batchSize)}`);
|
|
253
|
+
}
|
|
254
|
+
const a = agent;
|
|
255
|
+
if (!a?.provider || typeof a.provider.runEncoder !== "function" || !a?.tok || typeof a.tok.encode !== "function") {
|
|
256
|
+
throw new Error("embedFnFromAgent needs encoder access: agent.provider.runEncoder + agent.tok.encode required");
|
|
257
|
+
}
|
|
258
|
+
const tok = a.tok;
|
|
259
|
+
const provider = a.provider;
|
|
260
|
+
return async (texts) => {
|
|
261
|
+
const rows = (texts ?? []).map((t) => (t === null || t === undefined ? "" : String(t)));
|
|
262
|
+
if (rows.length === 0)
|
|
263
|
+
return [];
|
|
264
|
+
const out = [];
|
|
265
|
+
for (let s = 0; s < rows.length; s += batchSize) {
|
|
266
|
+
const chunk = rows.slice(s, s + batchSize);
|
|
267
|
+
const ids = chunk.map((t) => tok.encode(t).slice(0, maxLength));
|
|
268
|
+
const L = maxOf(ids.map((r) => r.length), 1);
|
|
269
|
+
const pad = tok.padId ?? 0;
|
|
270
|
+
const batch = {
|
|
271
|
+
inputIds: ids.map((r) => [...r, ...Array(L - r.length).fill(pad)]),
|
|
272
|
+
attentionMask: ids.map((r) => [...Array(r.length).fill(1), ...Array(L - r.length).fill(0)]),
|
|
273
|
+
markerPos: ids.map(() => [0]),
|
|
274
|
+
markerMask: ids.map(() => [true]),
|
|
275
|
+
qtype: ids.map(() => 0),
|
|
276
|
+
};
|
|
277
|
+
const { lastHidden } = await provider.runEncoder(batch);
|
|
278
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
279
|
+
const mask = batch.attentionMask[i];
|
|
280
|
+
const denom = Math.max(1, mask.reduce((x, y) => x + y, 0));
|
|
281
|
+
const dim = lastHidden[i]?.[0] ? lastHidden[i][0].length : 0;
|
|
282
|
+
const pooled = new Array(dim).fill(0);
|
|
283
|
+
for (let j = 0; j < mask.length; j++) {
|
|
284
|
+
if (!mask[j])
|
|
285
|
+
continue;
|
|
286
|
+
const hv = lastHidden[i]?.[j];
|
|
287
|
+
if (!hv)
|
|
288
|
+
continue;
|
|
289
|
+
for (let h = 0; h < dim; h++)
|
|
290
|
+
pooled[h] += Number(hv[h] ?? 0);
|
|
291
|
+
}
|
|
292
|
+
out.push(pooled.map((v) => v / denom));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return out;
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Wrap `embedFn` with an LRU cache keyed by text.
|
|
300
|
+
*
|
|
301
|
+
* Shortlisting embeds the query plus every option on every call. When the option
|
|
302
|
+
* set is fixed -- a label list, an intent taxonomy -- those rows never change
|
|
303
|
+
* between requests and are re-embedded every time. Wrapping the embedder once
|
|
304
|
+
* leaves the first call unchanged and reduces each repeat to embedding the new
|
|
305
|
+
* query alone.
|
|
306
|
+
*
|
|
307
|
+
* A cold cache costs the same number of embedder calls as the unwrapped function:
|
|
308
|
+
* the misses are deduplicated and embedded in one call. Nothing is cached when
|
|
309
|
+
* the embedder throws or returns a bad shape, so a transient failure cannot
|
|
310
|
+
* poison the cache.
|
|
311
|
+
*
|
|
312
|
+
* @param embedFn The underlying embedding function
|
|
313
|
+
* @param maxsize Maximum number of distinct text rows to cache (default: 4096)
|
|
314
|
+
*/
|
|
315
|
+
export function cachedEmbedFn(embedFn, maxsize = DEFAULT_SHORTLIST_MAXSIZE) {
|
|
316
|
+
if (typeof embedFn !== "function") {
|
|
317
|
+
throw new TypeError("embed_fn must be callable");
|
|
318
|
+
}
|
|
319
|
+
if (typeof maxsize !== "number" || !Number.isInteger(maxsize) || maxsize < 1) {
|
|
320
|
+
throw new Error(`maxsize must be a positive integer, got ${JSON.stringify(maxsize)}`);
|
|
321
|
+
}
|
|
322
|
+
const rowsByText = new Map();
|
|
323
|
+
let hitsTotal = 0;
|
|
324
|
+
let missesTotal = 0;
|
|
325
|
+
let generation = 0;
|
|
326
|
+
const fn = async (texts) => {
|
|
327
|
+
const keys = (texts ?? []).map((t) => (t === null || t === undefined ? "" : String(t)));
|
|
328
|
+
if (keys.length === 0)
|
|
329
|
+
return [];
|
|
330
|
+
const found = new Map();
|
|
331
|
+
let hitsThisCall = 0;
|
|
332
|
+
for (const key of keys) {
|
|
333
|
+
const row = rowsByText.get(key);
|
|
334
|
+
if (row !== undefined) {
|
|
335
|
+
found.set(key, row);
|
|
336
|
+
hitsThisCall++;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
hitsTotal += hitsThisCall;
|
|
340
|
+
missesTotal += keys.length - hitsThisCall;
|
|
341
|
+
const missing = [];
|
|
342
|
+
const seenMissing = new Set();
|
|
343
|
+
for (const key of keys) {
|
|
344
|
+
if (!found.has(key) && !seenMissing.has(key)) {
|
|
345
|
+
seenMissing.add(key);
|
|
346
|
+
missing.push(key);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const genAtStart = generation;
|
|
350
|
+
if (missing.length > 0) {
|
|
351
|
+
const fresh = await embeddings(embedFn, missing);
|
|
352
|
+
// Validate dimensions of all returned rows before caching any
|
|
353
|
+
const heldDim = rowsByText.size > 0 ? rowsByText.values().next().value?.length : undefined;
|
|
354
|
+
const expectedDim = heldDim ?? (fresh.length > 0 ? fresh[0]?.length : undefined);
|
|
355
|
+
for (let i = 0; i < fresh.length; i++) {
|
|
356
|
+
const rowDim = fresh[i]?.length ?? 0;
|
|
357
|
+
if (expectedDim !== undefined && rowDim !== expectedDim) {
|
|
358
|
+
if (heldDim !== undefined) {
|
|
359
|
+
throw new Error(`the embedder returned dim ${rowDim}, but the cache holds dim ${heldDim}; call cacheClear() if the model behind it changed`);
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
throw new Error(`the embedder returned inconsistent embedding dimensions (${expectedDim} vs ${rowDim})`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
for (let i = 0; i < missing.length; i++) {
|
|
367
|
+
found.set(missing[i], fresh[i]);
|
|
368
|
+
}
|
|
369
|
+
// If cacheClear() ran while embeddings() was pending, do not restore entries into the cleared cache
|
|
370
|
+
if (generation !== genAtStart) {
|
|
371
|
+
return keys.map((key) => [...(found.get(key) ?? [])]);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// Apply recency updates and evictions in input key order
|
|
375
|
+
for (const key of keys) {
|
|
376
|
+
const row = found.get(key);
|
|
377
|
+
if (row !== undefined) {
|
|
378
|
+
rowsByText.delete(key);
|
|
379
|
+
rowsByText.set(key, row);
|
|
380
|
+
while (rowsByText.size > maxsize) {
|
|
381
|
+
const victim = rowsByText.keys().next().value;
|
|
382
|
+
rowsByText.delete(victim);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return keys.map((key) => [...(found.get(key) ?? [])]);
|
|
387
|
+
};
|
|
388
|
+
const cacheInfo = () => ({
|
|
389
|
+
size: rowsByText.size,
|
|
390
|
+
maxsize,
|
|
391
|
+
hits: hitsTotal,
|
|
392
|
+
misses: missesTotal,
|
|
393
|
+
});
|
|
394
|
+
const cacheClear = () => {
|
|
395
|
+
rowsByText.clear();
|
|
396
|
+
hitsTotal = 0;
|
|
397
|
+
missesTotal = 0;
|
|
398
|
+
generation++;
|
|
399
|
+
};
|
|
400
|
+
const cachedResult = fn;
|
|
401
|
+
cachedResult.cacheInfo = cacheInfo;
|
|
402
|
+
cachedResult.cache_info = cacheInfo;
|
|
403
|
+
cachedResult.cacheClear = cacheClear;
|
|
404
|
+
cachedResult.cache_clear = cacheClear;
|
|
405
|
+
return cachedResult;
|
|
406
|
+
}
|
|
407
|
+
export const cached = cachedEmbedFn;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-driven decisions: turn a JSON schema into Laya questions.
|
|
3
|
+
*
|
|
4
|
+
* Port of `laya/structured.py` (#280). Provider-free. The mapping is a documented subset:
|
|
5
|
+
* an object of properties, each an enum choice, a boolean, or a bounded integer scale.
|
|
6
|
+
* Anything that cannot be answered from a fixed option set (free strings, arrays, nested
|
|
7
|
+
* objects, $ref) is rejected with a SchemaError that names the path.
|
|
8
|
+
*
|
|
9
|
+
* const values = await agent.decide(state, {
|
|
10
|
+
* type: "object",
|
|
11
|
+
* properties: {
|
|
12
|
+
* department: { type: "string", enum: ["billing", "support", "sales"] },
|
|
13
|
+
* urgency: { type: "integer", minimum: 0, maximum: 2 },
|
|
14
|
+
* needs_human: { type: "boolean" },
|
|
15
|
+
* },
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* Zod/TypeBox users can pass their schema's JSON form (`z.toJSONSchema(Model)`); anything
|
|
19
|
+
* with a `toJSONSchema()` method is accepted.
|
|
20
|
+
*/
|
|
21
|
+
import type { QuestionDef } from "./agent.js";
|
|
22
|
+
import type { MinConfidence } from "./common.js";
|
|
23
|
+
export declare const MAX_PROPERTIES = 32;
|
|
24
|
+
export declare const MAX_OPTIONS = 32;
|
|
25
|
+
export declare const MAX_SCORE_LEVELS = 10;
|
|
26
|
+
/** A schema cannot be expressed as Laya questions; the message names the path. */
|
|
27
|
+
export declare class SchemaError extends Error {
|
|
28
|
+
constructor(message: string);
|
|
29
|
+
}
|
|
30
|
+
/** The detailed result of `decide(..., { returnDetails: true })`. */
|
|
31
|
+
export interface DecisionResult {
|
|
32
|
+
/** Schema-shaped output (choice values, integer levels, booleans). */
|
|
33
|
+
values: Record<string, unknown>;
|
|
34
|
+
/** Per-field confidence. */
|
|
35
|
+
confidence: Record<string, number>;
|
|
36
|
+
/** Per-field probabilities (noul fields report { false, true }). */
|
|
37
|
+
probabilities: Record<string, Record<string, unknown>>;
|
|
38
|
+
/** Laya's raw answer per field. */
|
|
39
|
+
answers: Record<string, unknown>;
|
|
40
|
+
usage?: unknown;
|
|
41
|
+
routing?: unknown;
|
|
42
|
+
}
|
|
43
|
+
/** One planned field: the Laya question plus how to project its answer back. */
|
|
44
|
+
export interface PlannedField {
|
|
45
|
+
name: string;
|
|
46
|
+
kind: "choice" | "score" | "noul";
|
|
47
|
+
question: QuestionDef;
|
|
48
|
+
/** choice: (label, value) pairs, in enum order. */
|
|
49
|
+
options?: [string, unknown][];
|
|
50
|
+
/** score: value of level 0. */
|
|
51
|
+
minimum?: number;
|
|
52
|
+
}
|
|
53
|
+
/** Anything with an async predict(state, questions, opts) — Agent and Router both qualify. */
|
|
54
|
+
export interface DecideRunner {
|
|
55
|
+
predict(state: unknown, questions: Record<string, QuestionDef>, opts?: Record<string, unknown>): Promise<{
|
|
56
|
+
answers?: Record<string, Record<string, any> | undefined>;
|
|
57
|
+
usage?: unknown;
|
|
58
|
+
routing?: unknown;
|
|
59
|
+
}>;
|
|
60
|
+
}
|
|
61
|
+
export interface DecideOptions {
|
|
62
|
+
/** Explicit questions instead of a schema (answers are returned unprojected). */
|
|
63
|
+
questions?: Record<string, QuestionDef>;
|
|
64
|
+
/** Return a DecisionResult with confidence, probabilities and raw answers. */
|
|
65
|
+
returnDetails?: boolean;
|
|
66
|
+
/** Minimum confidence threshold in [0.0, 1.0] or per-bucket map. Low confidence answers project to null. */
|
|
67
|
+
minConfidence?: MinConfidence | null;
|
|
68
|
+
/** Python parity alias for minConfidence. */
|
|
69
|
+
min_confidence?: MinConfidence | null;
|
|
70
|
+
/** Anything else is forwarded to runner.predict (hooks, model, ...). */
|
|
71
|
+
[k: string]: unknown;
|
|
72
|
+
}
|
|
73
|
+
/** Validate a JSON schema and return one planned field per property. */
|
|
74
|
+
export declare function planFromJsonSchema(schema: unknown): PlannedField[];
|
|
75
|
+
/** Turn a JSON schema into Laya questions (a documented subset; see the module docstring). */
|
|
76
|
+
export declare function questionsFromJsonSchema(schema: unknown): Record<string, QuestionDef>;
|
|
77
|
+
/** Project Laya answers onto the schema values (choice value, integer level, boolean). */
|
|
78
|
+
export declare function answersToJson(answers: Record<string, Record<string, any> | undefined>, schema: unknown): Record<string, unknown>;
|
|
79
|
+
/**
|
|
80
|
+
* Answer `state` against a schema (or explicit questions) and return the decided values.
|
|
81
|
+
*
|
|
82
|
+
* Pass exactly one of `schema` or `opts.questions`. With `schema`, the values follow the
|
|
83
|
+
* schema (choice values, integer levels, booleans). With `questions`, the raw answers are
|
|
84
|
+
* returned. Extra options are forwarded to `runner.predict`.
|
|
85
|
+
*/
|
|
86
|
+
export declare function decide(runner: DecideRunner, state: unknown, schema: unknown, opts: DecideOptions & {
|
|
87
|
+
returnDetails: true;
|
|
88
|
+
}): Promise<DecisionResult>;
|
|
89
|
+
export declare function decide(runner: DecideRunner, state: unknown, schema?: unknown, opts?: DecideOptions): Promise<Record<string, unknown>>;
|