@dbx-tools/dbx-model-catalog 0.1.9 → 0.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.
- package/README.md +10 -6
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +93 -9026
- package/dist/cli.js +181 -9114
- package/dist/index.d.ts +1 -1
- package/dist/index.js +117 -9087
- package/dist/pynect.js +6 -2
- package/package.json +4 -7
- package/src/_generated/channels.ts +38 -0
- package/src/_generated/index.ts +6 -0
- package/src/_generated/json-schema.ts +3 -0
- package/src/_generated/published.ts +7 -0
- package/src/_generated/schemas.ts +408 -0
- package/src/browser.ts +64 -0
- package/src/catalog-index.ts +94 -0
- package/src/cli.ts +102 -0
- package/src/filter.ts +47 -0
- package/src/identity.ts +79 -0
- package/src/index.ts +114 -0
- package/src/local-client.ts +51 -0
- package/src/pynect.ts +68 -0
- package/src/search.ts +534 -0
- package/src/types.ts +19 -0
- package/src/validation.ts +94 -0
- package/dist/browser.js.map +0 -38
- package/dist/catalog.json +0 -1
- package/dist/cli.js.map +0 -40
- package/dist/index.js.map +0 -39
- package/dist/pynect.js.map +0 -15
- package/dist/search-index.json +0 -1
- package/dist/snapshot.d.ts +0 -7
- package/dist/snapshot.js +0 -9515
- package/dist/snapshot.js.map +0 -36
package/src/search.ts
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CatalogModelRecord,
|
|
3
|
+
CatalogSearchIndexDocument,
|
|
4
|
+
CatalogSearchIndexPayload,
|
|
5
|
+
} from "./_generated/schemas.js";
|
|
6
|
+
|
|
7
|
+
// The fuzzy string scoring formulas follow RapidFuzz's MIT-licensed behavior.
|
|
8
|
+
// Copyright (C) 2022 Max Bachmann and RapidFuzz contributors.
|
|
9
|
+
|
|
10
|
+
interface SearchField {
|
|
11
|
+
readonly identity: boolean;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly value: string;
|
|
14
|
+
readonly weight: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface FieldScore {
|
|
18
|
+
readonly field: SearchField;
|
|
19
|
+
readonly kind: "exact" | "fuzzy" | "token";
|
|
20
|
+
readonly score: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CatalogSearchMatch {
|
|
24
|
+
readonly exact: boolean;
|
|
25
|
+
readonly kind: "exact" | "fuzzy" | "token";
|
|
26
|
+
readonly record: CatalogModelRecord;
|
|
27
|
+
readonly relevance: number;
|
|
28
|
+
readonly score: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface ScoredRecord extends CatalogSearchMatch {
|
|
32
|
+
readonly identityExact: boolean;
|
|
33
|
+
readonly record: CatalogModelRecord;
|
|
34
|
+
readonly relevance: number;
|
|
35
|
+
readonly releaseDate: string | null;
|
|
36
|
+
readonly score: number;
|
|
37
|
+
readonly version: number[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const neutralScore = 50;
|
|
41
|
+
const statusPriority = new Map([
|
|
42
|
+
"active",
|
|
43
|
+
"preview",
|
|
44
|
+
"beta",
|
|
45
|
+
"alpha",
|
|
46
|
+
"legacy",
|
|
47
|
+
"deprecated",
|
|
48
|
+
"retired",
|
|
49
|
+
].map((status, index) => [status, index]));
|
|
50
|
+
const tokenPattern = /[a-z]+|\d+/g;
|
|
51
|
+
const versionPattern = /(?:^|[^a-z0-9])(\d+)(?:[.\-_](\d+))?(?:[.\-_](\d+))?(?![a-z0-9])/i;
|
|
52
|
+
|
|
53
|
+
export function searchCatalogRecords<T extends CatalogModelRecord>(
|
|
54
|
+
index: CatalogSearchIndexPayload,
|
|
55
|
+
models: readonly T[],
|
|
56
|
+
query: string,
|
|
57
|
+
limit: number | null = 50,
|
|
58
|
+
): T[] {
|
|
59
|
+
return searchCatalogMatches(index, models, query, limit).map(match => match.record as T);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function searchCatalogMatches<T extends CatalogModelRecord>(
|
|
63
|
+
index: CatalogSearchIndexPayload,
|
|
64
|
+
models: readonly T[],
|
|
65
|
+
query: string,
|
|
66
|
+
limit: number | null = 50,
|
|
67
|
+
): CatalogSearchMatch[] {
|
|
68
|
+
const normalizedQuery = normalizeSearch(query);
|
|
69
|
+
if (!normalizedQuery || limit === 0) return [];
|
|
70
|
+
const queryTokens = tokens(normalizedQuery).filter(token => !/^\d+$/.test(token));
|
|
71
|
+
const requestedVersion = version(query);
|
|
72
|
+
const documentById = new Map(index.documents.map(document => [document.id, document]));
|
|
73
|
+
const referenceDate = index.updated_at.slice(0, 10);
|
|
74
|
+
const scored = models.flatMap(model => {
|
|
75
|
+
const document = documentById.get(model.id);
|
|
76
|
+
if (!document) return [];
|
|
77
|
+
const candidate = scoreRecord(
|
|
78
|
+
model,
|
|
79
|
+
document,
|
|
80
|
+
index,
|
|
81
|
+
normalizedQuery,
|
|
82
|
+
queryTokens,
|
|
83
|
+
requestedVersion,
|
|
84
|
+
referenceDate,
|
|
85
|
+
);
|
|
86
|
+
return candidate ? [candidate] : [];
|
|
87
|
+
});
|
|
88
|
+
scored.sort((left, right) => compareScored(left, right, requestedVersion));
|
|
89
|
+
const results = scored.map(({ identityExact: _identityExact, releaseDate: _releaseDate, version: _version, ...candidate }) => candidate);
|
|
90
|
+
return limit === null ? results : results.slice(0, limit);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function scoreRecord(
|
|
94
|
+
record: CatalogModelRecord,
|
|
95
|
+
document: CatalogSearchIndexDocument,
|
|
96
|
+
index: CatalogSearchIndexPayload,
|
|
97
|
+
query: string,
|
|
98
|
+
queryTokens: string[],
|
|
99
|
+
requestedVersion: number[],
|
|
100
|
+
referenceDate: string,
|
|
101
|
+
): ScoredRecord | undefined {
|
|
102
|
+
const fields = searchFields(record);
|
|
103
|
+
const fieldScores = fields.map(field => scoreField(field, query, new Set(queryTokens)));
|
|
104
|
+
const tokenScores = queryTokenScores(queryTokens, document.tokens);
|
|
105
|
+
if (!passesTokenGate(queryTokens, tokenScores, document.identities, requestedVersion.length > 0)) {
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
const relevance = Math.max(
|
|
109
|
+
...fieldScores.map(item => item.score),
|
|
110
|
+
tokenScores.length ? mean(tokenScores) * 0.94 : 0,
|
|
111
|
+
);
|
|
112
|
+
if (relevance < 58) return undefined;
|
|
113
|
+
|
|
114
|
+
const leading = fieldScores.filter(item => item.score >= relevance - 8);
|
|
115
|
+
const identityMatch = (
|
|
116
|
+
queryTokens.length > 0
|
|
117
|
+
&& queryTokens.every(token => document.identities.some(identity => tokens(identity).includes(token)))
|
|
118
|
+
) || leading.some(item => item.field.identity);
|
|
119
|
+
const identityExact = leading.some(item =>
|
|
120
|
+
item.kind === "exact" && ["id", "name", "alias"].includes(item.field.name),
|
|
121
|
+
);
|
|
122
|
+
const quality = {
|
|
123
|
+
leaderboard: leaderboardScore(record, queryTokens, referenceDate),
|
|
124
|
+
benchmark: benchmarkScore(record, queryTokens, referenceDate),
|
|
125
|
+
version: requestedVersion.length
|
|
126
|
+
? requestedVersionScore(document.version, requestedVersion)
|
|
127
|
+
: identityMatch ? document.scores.version : neutralScore,
|
|
128
|
+
freshness: document.scores.freshness,
|
|
129
|
+
lifecycle: document.scores.lifecycle,
|
|
130
|
+
};
|
|
131
|
+
const combined = round3(
|
|
132
|
+
relevance * index.weights.relevance
|
|
133
|
+
+ quality.leaderboard * index.weights.leaderboard
|
|
134
|
+
+ quality.benchmark * index.weights.benchmark
|
|
135
|
+
+ quality.version * index.weights.version
|
|
136
|
+
+ quality.freshness * index.weights.freshness
|
|
137
|
+
+ quality.lifecycle * index.weights.lifecycle,
|
|
138
|
+
);
|
|
139
|
+
return {
|
|
140
|
+
exact: identityExact,
|
|
141
|
+
identityExact,
|
|
142
|
+
kind: identityExact ? "exact" : leading.some(item => item.kind === "token") ? "token" : "fuzzy",
|
|
143
|
+
record,
|
|
144
|
+
relevance: round3(relevance),
|
|
145
|
+
releaseDate: record.release_date ?? null,
|
|
146
|
+
score: combined,
|
|
147
|
+
version: document.version,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function scoreField(field: SearchField, query: string, requestedTokens: Set<string>): FieldScore {
|
|
152
|
+
const weighted = Math.max(weightedRatio(query, field.value), tokenSetRatio(query, field.value))
|
|
153
|
+
* field.weight;
|
|
154
|
+
if (query === field.value) return { field, kind: "exact", score: 100 };
|
|
155
|
+
if (field.value.includes(query)) {
|
|
156
|
+
return { field, kind: "token", score: Math.max(weighted, 96 * field.weight) };
|
|
157
|
+
}
|
|
158
|
+
const fieldTokens = new Set(tokens(field.value));
|
|
159
|
+
if (requestedTokens.size > 0 && [...requestedTokens].every(token => fieldTokens.has(token))) {
|
|
160
|
+
return { field, kind: "token", score: Math.max(weighted, 94 * field.weight) };
|
|
161
|
+
}
|
|
162
|
+
return { field, kind: "fuzzy", score: weighted };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function passesTokenGate(
|
|
166
|
+
queryTokens: string[],
|
|
167
|
+
tokenScores: number[],
|
|
168
|
+
identities: string[],
|
|
169
|
+
requireIdentity: boolean,
|
|
170
|
+
): boolean {
|
|
171
|
+
if (queryTokens.some((token, index) => (tokenScores[index] ?? 0) < (token.length <= 3 ? 80 : 65))) {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
if (!requireIdentity || queryTokens.length === 0) return true;
|
|
175
|
+
const identityTokens = new Set(identities.flatMap(identity => tokens(identity)));
|
|
176
|
+
return Math.min(...queryTokenScores(queryTokens, [...identityTokens])) >= 75;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function queryTokenScores(queryTokens: string[], candidateTokens: readonly string[]): number[] {
|
|
180
|
+
return queryTokens.map(token => Math.max(0, ...candidateTokens.map(candidate => ratio(token, candidate))));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function compareScored(left: ScoredRecord, right: ScoredRecord, requestedVersion: number[]): number {
|
|
184
|
+
if (left.identityExact !== right.identityExact) return left.identityExact ? -1 : 1;
|
|
185
|
+
if (requestedVersion.length) {
|
|
186
|
+
const distance = compareNumbers(
|
|
187
|
+
versionDistance(left.version, requestedVersion),
|
|
188
|
+
versionDistance(right.version, requestedVersion),
|
|
189
|
+
);
|
|
190
|
+
if (distance) return distance;
|
|
191
|
+
}
|
|
192
|
+
return right.score - left.score
|
|
193
|
+
|| right.relevance - left.relevance
|
|
194
|
+
|| (statusPriority.get(left.record.status) ?? statusPriority.size)
|
|
195
|
+
- (statusPriority.get(right.record.status) ?? statusPriority.size)
|
|
196
|
+
|| compareOptionalDateDescending(left.releaseDate, right.releaseDate)
|
|
197
|
+
|| compareText(left.record.name, right.record.name)
|
|
198
|
+
|| compareText(left.record.id, right.record.id);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function searchFields(record: CatalogModelRecord): SearchField[] {
|
|
202
|
+
const fields: SearchField[] = [
|
|
203
|
+
field("id", record.id, 1, true),
|
|
204
|
+
field("name", record.name, 1, true),
|
|
205
|
+
...record.aliases.map(value => field("alias", value, 1, true)),
|
|
206
|
+
field("publisher", record.publisher ?? "", 0.98, true),
|
|
207
|
+
field("family", record.family ?? "", 0.98, true),
|
|
208
|
+
field("type", record.type, 0.9),
|
|
209
|
+
field("status", record.status, 0.86),
|
|
210
|
+
field("license", record.license ?? "", 0.84),
|
|
211
|
+
...record.tasks.map(value => field("task", value, 0.94)),
|
|
212
|
+
...record.use_cases.map(value => field("use case", value, 0.94)),
|
|
213
|
+
...record.modalities.input.map(value => field("input modality", value, 0.9)),
|
|
214
|
+
...record.modalities.output.map(value => field("output modality", value, 0.9)),
|
|
215
|
+
...record.rankings.map(value => field("leaderboard domain", value.domain, 0.92)),
|
|
216
|
+
...record.rankings.map(value => field("leaderboard category", value.category, 0.88)),
|
|
217
|
+
...record.benchmarks.map(value => field("benchmark", value.name, 0.92)),
|
|
218
|
+
field("description", record.description, 0.76),
|
|
219
|
+
];
|
|
220
|
+
|
|
221
|
+
for (const [name, value] of Object.entries(record.capabilities)) {
|
|
222
|
+
const objectValue = isRecord(value) ? value : undefined;
|
|
223
|
+
if (value === true || objectValue?.supported === true) {
|
|
224
|
+
fields.push(field("capability", name.replaceAll("_", " "), 0.94));
|
|
225
|
+
}
|
|
226
|
+
if (name === "reasoning" && objectValue) {
|
|
227
|
+
const effort = Array.isArray(objectValue.effort) ? objectValue.effort : [];
|
|
228
|
+
for (const level of effort) fields.push(field("reasoning effort", `${String(level)} reasoning`, 0.94));
|
|
229
|
+
if (objectValue.toggle === true) fields.push(field("reasoning control", "reasoning toggle", 0.92));
|
|
230
|
+
if (objectValue.budget) fields.push(field("reasoning control", "reasoning token budget", 0.92));
|
|
231
|
+
if (typeof objectValue.description === "string") {
|
|
232
|
+
fields.push(field("reasoning description", objectValue.description, 0.8));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
for (const [cloud, availability] of Object.entries(record.availability)) {
|
|
237
|
+
fields.push(field("cloud", cloud, 0.9));
|
|
238
|
+
fields.push(field("availability", availability.status, 0.82));
|
|
239
|
+
fields.push(...availability.serving_modes.map(mode => field("serving mode", mode, 0.9)));
|
|
240
|
+
if (availability.details) fields.push(field("availability details", availability.details, 0.72));
|
|
241
|
+
}
|
|
242
|
+
for (const notice of record.notices) {
|
|
243
|
+
fields.push(field("notice", notice.kind, 0.74));
|
|
244
|
+
fields.push(field("notice", notice.title ?? "", 0.74));
|
|
245
|
+
fields.push(field("notice", notice.text, 0.7));
|
|
246
|
+
}
|
|
247
|
+
return fields
|
|
248
|
+
.map(value => ({ ...value, value: normalizeSearch(value.value) }))
|
|
249
|
+
.filter(value => value.value.length > 0);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function field(name: string, value: string, weight: number, identity = false): SearchField {
|
|
253
|
+
return { identity, name, value, weight };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function leaderboardScore(record: CatalogModelRecord, queryTokens: string[], referenceDate: string): number {
|
|
257
|
+
const matched = record.rankings.filter(ranking => evidenceMatches(
|
|
258
|
+
queryTokens,
|
|
259
|
+
ranking.domain,
|
|
260
|
+
ranking.category,
|
|
261
|
+
));
|
|
262
|
+
const selected = matched.length
|
|
263
|
+
? matched
|
|
264
|
+
: record.rankings.filter(ranking => ranking.category.toLowerCase() === "overall");
|
|
265
|
+
if (!selected.length) return neutralScore;
|
|
266
|
+
return aggregateEvidence(selected.map(ranking => ageAdjustedScore(
|
|
267
|
+
rankScore(ranking.rank, 20),
|
|
268
|
+
ranking.published_at ?? null,
|
|
269
|
+
referenceDate,
|
|
270
|
+
180,
|
|
271
|
+
"votes" in ranking ? ranking.votes : ranking.observations,
|
|
272
|
+
5_000,
|
|
273
|
+
)));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function benchmarkScore(record: CatalogModelRecord, queryTokens: string[], referenceDate: string): number {
|
|
277
|
+
const matched = record.benchmarks.filter(benchmark => evidenceMatches(queryTokens, benchmark.name));
|
|
278
|
+
const selected = matched.length ? matched : record.benchmarks;
|
|
279
|
+
if (!selected.length) return neutralScore;
|
|
280
|
+
return aggregateEvidence(selected.map(benchmark => ageAdjustedScore(
|
|
281
|
+
rankScore(benchmark.rank, 10),
|
|
282
|
+
benchmark.published_at ?? null,
|
|
283
|
+
referenceDate,
|
|
284
|
+
365,
|
|
285
|
+
benchmark.task_count,
|
|
286
|
+
20,
|
|
287
|
+
)));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function evidenceMatches(queryTokens: string[], ...values: string[]): boolean {
|
|
291
|
+
if (!queryTokens.length) return false;
|
|
292
|
+
const evidence = new Set(tokens(normalizeSearch(values.join(" "))));
|
|
293
|
+
return queryTokens.some(token => evidence.has(token));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function ageAdjustedScore(
|
|
297
|
+
score: number,
|
|
298
|
+
publishedAt: string | null,
|
|
299
|
+
referenceDate: string,
|
|
300
|
+
halfLifeDays: number,
|
|
301
|
+
confidenceCount: number | null | undefined,
|
|
302
|
+
confidenceTarget: number,
|
|
303
|
+
): number {
|
|
304
|
+
const ageDays = publishedAt
|
|
305
|
+
? Math.max(0, dateDays(referenceDate) - dateDays(publishedAt))
|
|
306
|
+
: halfLifeDays;
|
|
307
|
+
const ageFactor = 0.5 ** (ageDays / halfLifeDays);
|
|
308
|
+
const confidence = confidenceCount === null || confidenceCount === undefined
|
|
309
|
+
? 0
|
|
310
|
+
: Math.min(1, Math.log1p(confidenceCount) / Math.log1p(confidenceTarget));
|
|
311
|
+
const evidenceFactor = ageFactor * (0.75 + confidence * 0.25);
|
|
312
|
+
return neutralScore + (score - neutralScore) * evidenceFactor;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function aggregateEvidence(scores: number[]): number {
|
|
316
|
+
if (!scores.length) return neutralScore;
|
|
317
|
+
const aggregate = median(scores) * 0.6 + mean(scores) * 0.4;
|
|
318
|
+
const coverageFactor = 0.85 + Math.min(scores.length, 5) / 5 * 0.15;
|
|
319
|
+
return neutralScore + (aggregate - neutralScore) * coverageFactor;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function requestedVersionScore(candidate: number[], requested: number[]): number {
|
|
323
|
+
if (!candidate.length) return 0;
|
|
324
|
+
const [candidateMajor = 0, candidateMinor = 0, candidatePatch = 0] = candidate;
|
|
325
|
+
const [requestedMajor = 0, requestedMinor = 0, requestedPatch = 0] = requested;
|
|
326
|
+
if (candidateMajor !== requestedMajor) {
|
|
327
|
+
return Math.max(0, 40 - Math.abs(candidateMajor - requestedMajor) * 15);
|
|
328
|
+
}
|
|
329
|
+
return Math.max(
|
|
330
|
+
0,
|
|
331
|
+
100
|
|
332
|
+
- Math.abs(candidateMinor - requestedMinor) * 15
|
|
333
|
+
- Math.abs(candidatePatch - requestedPatch) * 5,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function versionDistance(candidate: number[], requested: number[]): number[] {
|
|
338
|
+
if (!candidate.length) return [1, 1, 1_000, 1_000, 1_000];
|
|
339
|
+
const [candidateMajor = 0, candidateMinor = 0, candidatePatch = 0] = candidate;
|
|
340
|
+
const [requestedMajor = 0, requestedMinor = 0, requestedPatch = 0] = requested;
|
|
341
|
+
return [
|
|
342
|
+
0,
|
|
343
|
+
candidateMajor === requestedMajor ? 0 : 1,
|
|
344
|
+
Math.abs(candidateMajor - requestedMajor),
|
|
345
|
+
Math.abs(candidateMinor - requestedMinor),
|
|
346
|
+
Math.abs(candidatePatch - requestedPatch),
|
|
347
|
+
];
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function weightedRatio(left: string, right: string): number {
|
|
351
|
+
if (!left || !right) return 0;
|
|
352
|
+
const lengthRatio = Math.max(left.length, right.length) / Math.min(left.length, right.length);
|
|
353
|
+
const base = ratio(left, right);
|
|
354
|
+
if (lengthRatio < 1.5) {
|
|
355
|
+
return Math.max(base, tokenRatio(left, right) * 0.95);
|
|
356
|
+
}
|
|
357
|
+
const partialScale = lengthRatio <= 8 ? 0.9 : 0.6;
|
|
358
|
+
return Math.max(
|
|
359
|
+
base,
|
|
360
|
+
partialRatio(left, right) * partialScale,
|
|
361
|
+
partialTokenRatio(left, right) * 0.95 * partialScale,
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function tokenRatio(left: string, right: string): number {
|
|
366
|
+
return Math.max(tokenSetRatio(left, right), ratio(sortTokens(left), sortTokens(right)));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function partialTokenRatio(left: string, right: string): number {
|
|
370
|
+
const leftTokens = left.split(/\s+/).filter(Boolean);
|
|
371
|
+
const rightTokens = right.split(/\s+/).filter(Boolean);
|
|
372
|
+
const leftSet = new Set(leftTokens);
|
|
373
|
+
const rightSet = new Set(rightTokens);
|
|
374
|
+
if ([...leftSet].some(token => rightSet.has(token))) return 100;
|
|
375
|
+
const base = partialRatio([...leftTokens].sort().join(" "), [...rightTokens].sort().join(" "));
|
|
376
|
+
const leftDiff = [...leftSet].filter(token => !rightSet.has(token));
|
|
377
|
+
const rightDiff = [...rightSet].filter(token => !leftSet.has(token));
|
|
378
|
+
if (leftTokens.length === leftDiff.length && rightTokens.length === rightDiff.length) return base;
|
|
379
|
+
return Math.max(base, partialRatio(leftDiff.sort().join(" "), rightDiff.sort().join(" ")));
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function tokenSetRatio(left: string, right: string): number {
|
|
383
|
+
const leftSet = new Set(left.split(/\s+/).filter(Boolean));
|
|
384
|
+
const rightSet = new Set(right.split(/\s+/).filter(Boolean));
|
|
385
|
+
if (!leftSet.size || !rightSet.size) return 0;
|
|
386
|
+
const intersection = [...leftSet].filter(token => rightSet.has(token));
|
|
387
|
+
const leftDiff = [...leftSet].filter(token => !rightSet.has(token)).sort().join(" ");
|
|
388
|
+
const rightDiff = [...rightSet].filter(token => !leftSet.has(token)).sort().join(" ");
|
|
389
|
+
if (intersection.length && (!leftDiff || !rightDiff)) return 100;
|
|
390
|
+
const intersectionLength = intersection.join(" ").length;
|
|
391
|
+
const leftLength = intersectionLength + (intersectionLength ? 1 : 0) + leftDiff.length;
|
|
392
|
+
const rightLength = intersectionLength + (intersectionLength ? 1 : 0) + rightDiff.length;
|
|
393
|
+
const distance = indelDistance(leftDiff, rightDiff);
|
|
394
|
+
const differenceScore = normalizedDistanceScore(distance, leftLength + rightLength);
|
|
395
|
+
if (!intersectionLength) return differenceScore;
|
|
396
|
+
const leftIntersectionScore = normalizedDistanceScore(
|
|
397
|
+
1 + leftDiff.length,
|
|
398
|
+
intersectionLength + leftLength,
|
|
399
|
+
);
|
|
400
|
+
const rightIntersectionScore = normalizedDistanceScore(
|
|
401
|
+
1 + rightDiff.length,
|
|
402
|
+
intersectionLength + rightLength,
|
|
403
|
+
);
|
|
404
|
+
return Math.max(differenceScore, leftIntersectionScore, rightIntersectionScore);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function partialRatio(left: string, right: string): number {
|
|
408
|
+
if (!left && !right) return 100;
|
|
409
|
+
if (!left || !right) return 0;
|
|
410
|
+
const shorter = left.length <= right.length ? left : right;
|
|
411
|
+
const longer = left.length <= right.length ? right : left;
|
|
412
|
+
let best = 0;
|
|
413
|
+
for (let end = 1; end < shorter.length; end += 1) {
|
|
414
|
+
best = Math.max(best, ratio(shorter, longer.slice(0, end)));
|
|
415
|
+
}
|
|
416
|
+
for (let start = 0; start <= longer.length - shorter.length; start += 1) {
|
|
417
|
+
best = Math.max(best, ratio(shorter, longer.slice(start, start + shorter.length)));
|
|
418
|
+
}
|
|
419
|
+
for (let start = Math.max(0, longer.length - shorter.length + 1); start < longer.length; start += 1) {
|
|
420
|
+
best = Math.max(best, ratio(shorter, longer.slice(start)));
|
|
421
|
+
}
|
|
422
|
+
return best;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function ratio(left: string, right: string): number {
|
|
426
|
+
const total = left.length + right.length;
|
|
427
|
+
return total ? (2 * longestCommonSubsequence(left, right) / total) * 100 : 100;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function indelDistance(left: string, right: string): number {
|
|
431
|
+
return left.length + right.length - 2 * longestCommonSubsequence(left, right);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function longestCommonSubsequence(left: string, right: string): number {
|
|
435
|
+
if (!left || !right) return 0;
|
|
436
|
+
const needle = left.length <= right.length ? left : right;
|
|
437
|
+
const haystack = left.length <= right.length ? right : left;
|
|
438
|
+
const blocks = new Map<string, bigint>();
|
|
439
|
+
let bit = 1n;
|
|
440
|
+
for (const character of needle) {
|
|
441
|
+
blocks.set(character, (blocks.get(character) ?? 0n) | bit);
|
|
442
|
+
bit <<= 1n;
|
|
443
|
+
}
|
|
444
|
+
let state = (1n << BigInt(needle.length)) - 1n;
|
|
445
|
+
for (const character of haystack) {
|
|
446
|
+
const matches = blocks.get(character) ?? 0n;
|
|
447
|
+
const overlap = state & matches;
|
|
448
|
+
state = (state + overlap) | (state - overlap);
|
|
449
|
+
}
|
|
450
|
+
const mask = (1n << BigInt(needle.length)) - 1n;
|
|
451
|
+
return needle.length - popCount(state & mask);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function popCount(value: bigint): number {
|
|
455
|
+
let count = 0;
|
|
456
|
+
let current = value;
|
|
457
|
+
while (current) {
|
|
458
|
+
current &= current - 1n;
|
|
459
|
+
count += 1;
|
|
460
|
+
}
|
|
461
|
+
return count;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function normalizedDistanceScore(distance: number, lengthSum: number): number {
|
|
465
|
+
return lengthSum ? 100 - 100 * distance / lengthSum : 100;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function sortTokens(value: string): string {
|
|
469
|
+
return value.split(/\s+/).filter(Boolean).sort().join(" ");
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function normalizeSearch(value: string): string {
|
|
473
|
+
return (value.normalize("NFKC").toLowerCase().match(tokenPattern) ?? []).join(" ");
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function tokens(value: string): string[] {
|
|
477
|
+
return value.match(tokenPattern) ?? [];
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function version(value: string): number[] {
|
|
481
|
+
const match = versionPattern.exec(value.toLowerCase());
|
|
482
|
+
return match
|
|
483
|
+
? match.slice(1).filter((part): part is string => Boolean(part)).map(Number)
|
|
484
|
+
: [];
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function rankScore(rank: number, offset: number): number {
|
|
488
|
+
return (offset + 1) / (offset + rank) * 100;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function dateDays(value: string): number {
|
|
492
|
+
return Math.floor(Date.parse(`${value.slice(0, 10)}T00:00:00Z`) / 86_400_000);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function median(values: number[]): number {
|
|
496
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
497
|
+
const middle = Math.floor(sorted.length / 2);
|
|
498
|
+
return sorted.length % 2
|
|
499
|
+
? sorted[middle]!
|
|
500
|
+
: (sorted[middle - 1]! + sorted[middle]!) / 2;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function mean(values: readonly number[]): number {
|
|
504
|
+
return values.reduce((total, value) => total + value, 0) / values.length;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function round3(value: number): number {
|
|
508
|
+
return Math.round(value * 1_000) / 1_000;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function compareNumbers(left: number[], right: number[]): number {
|
|
512
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
513
|
+
const difference = (left[index] ?? 0) - (right[index] ?? 0);
|
|
514
|
+
if (difference) return difference;
|
|
515
|
+
}
|
|
516
|
+
return 0;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function compareOptionalDateDescending(left: string | null, right: string | null): number {
|
|
520
|
+
if (left === right) return 0;
|
|
521
|
+
if (left === null) return 1;
|
|
522
|
+
if (right === null) return -1;
|
|
523
|
+
return right.localeCompare(left);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function compareText(left: string, right: string): number {
|
|
527
|
+
const normalizedLeft = left.toLowerCase();
|
|
528
|
+
const normalizedRight = right.toLowerCase();
|
|
529
|
+
return normalizedLeft < normalizedRight ? -1 : normalizedLeft > normalizedRight ? 1 : 0;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
533
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
534
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CatalogFilters,
|
|
3
|
+
CatalogModelRecord,
|
|
4
|
+
CatalogSearchIndexPayload,
|
|
5
|
+
ModelCatalog,
|
|
6
|
+
} from "./_generated/schemas.js";
|
|
7
|
+
import type { CatalogIdentityMatch } from "./catalog-index.js";
|
|
8
|
+
import type { CatalogSearchMatch } from "./search.js";
|
|
9
|
+
|
|
10
|
+
export interface CatalogClient {
|
|
11
|
+
catalog(): Promise<ModelCatalog>;
|
|
12
|
+
searchIndex(): Promise<CatalogSearchIndexPayload>;
|
|
13
|
+
list(filters?: CatalogFilters): Promise<CatalogModelRecord[]>;
|
|
14
|
+
get(identity: string): Promise<CatalogModelRecord | undefined>;
|
|
15
|
+
resolve(identity: string): Promise<CatalogIdentityMatch | undefined>;
|
|
16
|
+
search(query: string, limit?: number | null): Promise<CatalogSearchMatch[]>;
|
|
17
|
+
stream(filters?: CatalogFilters): AsyncGenerator<CatalogModelRecord>;
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import {
|
|
3
|
+
CATALOG_SEARCH_INDEX_JSON_SCHEMA,
|
|
4
|
+
MODEL_CATALOG_JSON_SCHEMA,
|
|
5
|
+
} from "./_generated/json-schema.js";
|
|
6
|
+
import type {
|
|
7
|
+
AveragePrice,
|
|
8
|
+
Capabilities,
|
|
9
|
+
CatalogModel,
|
|
10
|
+
CatalogModelRecord,
|
|
11
|
+
CatalogSearchIndexPayload,
|
|
12
|
+
Latency,
|
|
13
|
+
ModelCatalog,
|
|
14
|
+
Price,
|
|
15
|
+
Rankings,
|
|
16
|
+
Rankings1,
|
|
17
|
+
RateLimits,
|
|
18
|
+
Status,
|
|
19
|
+
} from "./_generated/schemas.js";
|
|
20
|
+
|
|
21
|
+
type JsonSchemaInput = Parameters<typeof z.fromJSONSchema>[0];
|
|
22
|
+
type ModelCatalogDefinition = keyof typeof MODEL_CATALOG_JSON_SCHEMA.$defs;
|
|
23
|
+
|
|
24
|
+
function modelCatalogDefinitionSchema<T>(definition: ModelCatalogDefinition): z.ZodType<T> {
|
|
25
|
+
return z.fromJSONSchema({
|
|
26
|
+
...MODEL_CATALOG_JSON_SCHEMA.$defs[definition],
|
|
27
|
+
$defs: MODEL_CATALOG_JSON_SCHEMA.$defs,
|
|
28
|
+
} as unknown as JsonSchemaInput) as z.ZodType<T>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Runtime schema for the complete published model catalog. */
|
|
32
|
+
export const ModelCatalogSchema = z.fromJSONSchema(
|
|
33
|
+
MODEL_CATALOG_JSON_SCHEMA as unknown as JsonSchemaInput,
|
|
34
|
+
) as z.ZodType<ModelCatalog>;
|
|
35
|
+
|
|
36
|
+
/** Runtime schema for the published catalog search index. */
|
|
37
|
+
export const CatalogSearchIndexSchema = z.fromJSONSchema(
|
|
38
|
+
CATALOG_SEARCH_INDEX_JSON_SCHEMA as unknown as JsonSchemaInput,
|
|
39
|
+
) as z.ZodType<CatalogSearchIndexPayload>;
|
|
40
|
+
|
|
41
|
+
/** Runtime schema for one catalog model without its map key. */
|
|
42
|
+
export const CatalogModelSchema = modelCatalogDefinitionSchema<CatalogModel>("CatalogModel");
|
|
43
|
+
|
|
44
|
+
/** Runtime schema for one catalog model with its stable id. */
|
|
45
|
+
export const CatalogModelRecordSchema =
|
|
46
|
+
modelCatalogDefinitionSchema<CatalogModelRecord>("CatalogModelRecord");
|
|
47
|
+
|
|
48
|
+
/** Runtime schema for catalog-owned model capabilities. */
|
|
49
|
+
export const CatalogCapabilitiesSchema =
|
|
50
|
+
modelCatalogDefinitionSchema<Capabilities>("Capabilities");
|
|
51
|
+
|
|
52
|
+
/** Runtime schema for catalog-owned pay-per-token rate limits. */
|
|
53
|
+
export const CatalogRateLimitsSchema = modelCatalogDefinitionSchema<RateLimits>("RateLimits");
|
|
54
|
+
|
|
55
|
+
/** Runtime schema for catalog-owned latency measurements and score. */
|
|
56
|
+
export const CatalogLatencySchema = modelCatalogDefinitionSchema<Latency>("Latency");
|
|
57
|
+
|
|
58
|
+
/** Runtime schema for one catalog-owned cloud and currency price. */
|
|
59
|
+
export const CatalogPriceSchema = modelCatalogDefinitionSchema<Price>("Price");
|
|
60
|
+
|
|
61
|
+
/** Runtime schema for one catalog-owned normalized currency price. */
|
|
62
|
+
export const CatalogAveragePriceSchema =
|
|
63
|
+
modelCatalogDefinitionSchema<AveragePrice>("AveragePrice");
|
|
64
|
+
|
|
65
|
+
/** Runtime schema for a preference-rating ranking. */
|
|
66
|
+
export const CatalogPreferenceRankingSchema =
|
|
67
|
+
modelCatalogDefinitionSchema<Rankings>("Rankings");
|
|
68
|
+
|
|
69
|
+
/** Runtime schema for a scored-evaluation ranking. */
|
|
70
|
+
export const CatalogScoreRankingSchema = modelCatalogDefinitionSchema<Rankings1>("Rankings1");
|
|
71
|
+
|
|
72
|
+
/** Runtime schema for either catalog ranking representation. */
|
|
73
|
+
export const CatalogRankingSchema = z.union([
|
|
74
|
+
CatalogPreferenceRankingSchema,
|
|
75
|
+
CatalogScoreRankingSchema,
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
/** Runtime schema for a catalog model lifecycle status. */
|
|
79
|
+
export const CatalogStatusSchema = modelCatalogDefinitionSchema<Status>("Status");
|
|
80
|
+
|
|
81
|
+
/** Validate an untrusted catalog payload against the Python-owned contract. */
|
|
82
|
+
export function parseModelCatalog(value: unknown): ModelCatalog {
|
|
83
|
+
return ModelCatalogSchema.parse(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Validate an untrusted search-index payload against the Python-owned contract. */
|
|
87
|
+
export function parseCatalogSearchIndex(value: unknown): CatalogSearchIndexPayload {
|
|
88
|
+
return CatalogSearchIndexSchema.parse(value);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Validate one untrusted catalog model record. */
|
|
92
|
+
export function parseCatalogModelRecord(value: unknown): CatalogModelRecord {
|
|
93
|
+
return CatalogModelRecordSchema.parse(value);
|
|
94
|
+
}
|