@dbx-tools/model 0.1.58 → 0.1.68

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/index.ts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * `@dbx-tools/model` public surface.
3
- *
4
- * Bundles the package's Node-side Model Serving access (cached
5
- * `/serving-endpoints` listing plus fuzzy name resolution), the
6
- * workspace-aware {@link resolveModel} selector, and the server-only
7
- * offline fallback opinion (`FALLBACK_MODEL_IDS` / `modelsForClass`)
8
- * with a re-export of the pure `@dbx-tools/model-shared` surface
9
- * (capability tiers, the score profile, the endpoint descriptor, and
10
- * the tier classifier) so a single `from "@dbx-tools/model"` import
11
- * serves server-side consumers.
12
- *
13
- * Browser-side consumers should import `@dbx-tools/model-shared`
14
- * directly: the serving driver pulls in `WorkspaceClient` and AppKit's
15
- * `CacheManager` and is Node-only, whereas the re-exported surface is
16
- * pure (types + sync functions) and safe for any runtime.
17
- */
18
-
19
- export * from "@dbx-tools/model-shared";
20
- export * from "./src/classes.js";
21
- export * from "./src/fallback.js";
22
- export * from "./src/resolve.js";
23
- export * from "./src/serving.js";
package/src/classes.ts DELETED
@@ -1,75 +0,0 @@
1
- /**
2
- * Model-class ordering for the model service.
3
- *
4
- * `@dbx-tools/model-shared` declares the {@link ModelClass} values and
5
- * their schema; the *behavior* over those values - the chat capability
6
- * order, the "this class and below" ceiling, and coercing loose request
7
- * input to a class - lives here in the service so the shared
8
- * wire-format surface stays purely declarative.
9
- */
10
-
11
- import { ModelClass, ModelClassSchema } from "@dbx-tools/model-shared";
12
-
13
- /**
14
- * Chat capability ladder in descending order - most capable
15
- * ({@link ModelClass.ChatThinking}) first, least
16
- * ({@link ModelClass.ChatFast}) last. {@link ModelClass.Embedding} is a
17
- * separate modality and is deliberately absent: the ceiling never spans
18
- * it. This is the order used to filter "this class and below" and to
19
- * break ranking ties toward the more capable model.
20
- */
21
- export const CHAT_CLASS_ORDER: readonly ModelClass[] = [
22
- ModelClass.ChatThinking,
23
- ModelClass.ChatBalanced,
24
- ModelClass.ChatFast,
25
- ];
26
-
27
- /**
28
- * Every class in display order: the chat ladder followed by
29
- * {@link ModelClass.Embedding}. Used when flattening a full
30
- * classification (e.g. stamping the class onto each cached endpoint).
31
- */
32
- export const MODEL_CLASS_ORDER: readonly ModelClass[] = [
33
- ...CHAT_CLASS_ORDER,
34
- ModelClass.Embedding,
35
- ];
36
-
37
- /** Whether `cls` is one of the chat capability bands (vs. embedding). */
38
- export function isChatClass(cls: ModelClass): boolean {
39
- return CHAT_CLASS_ORDER.includes(cls);
40
- }
41
-
42
- /**
43
- * Coerce an arbitrary value (query string, header, body field) to a
44
- * {@link ModelClass}, returning `null` when it isn't a known class.
45
- * Lets a route accept a class request without throwing on junk input.
46
- *
47
- * Matches the full slug first (`"chat-fast"`, `"embedding"`), then -
48
- * for a bare chat band - retries with a `chat-` prefix, so the shorthand
49
- * `"thinking"` / `"balanced"` / `"fast"` resolves to the corresponding
50
- * `chat-*` class.
51
- */
52
- export function parseModelClass(value: unknown): ModelClass | null {
53
- const exact = ModelClassSchema.safeParse(value);
54
- if (exact.success) return exact.data;
55
- const prefixed = ModelClassSchema.safeParse(`chat-${value}`);
56
- return prefixed.success ? prefixed.data : null;
57
- }
58
-
59
- /**
60
- * Classes at or below `cls` in chat capability: the class itself plus
61
- * every less-capable chat band, in {@link CHAT_CLASS_ORDER}. Treats a
62
- * chat `cls` as a ceiling - requesting {@link ModelClass.ChatBalanced}
63
- * yields `[ChatBalanced, ChatFast]`, never
64
- * {@link ModelClass.ChatThinking} - so a class ask can degrade downward
65
- * to a smaller chat model but never escalate to a larger one.
66
- *
67
- * {@link ModelClass.Embedding} is its own modality, not a rung on the
68
- * chat ladder, so it yields just `[Embedding]`. An unrecognized class
69
- * yields the full chat ladder.
70
- */
71
- export function classesAtOrBelow(cls: ModelClass): ModelClass[] {
72
- if (cls === ModelClass.Embedding) return [ModelClass.Embedding];
73
- const index = CHAT_CLASS_ORDER.indexOf(cls);
74
- return index < 0 ? [...CHAT_CLASS_ORDER] : [...CHAT_CLASS_ORDER.slice(index)];
75
- }
package/src/fallback.ts DELETED
@@ -1,77 +0,0 @@
1
- /**
2
- * Server-side offline fallback opinion for model selection.
3
- *
4
- * When the live `/serving-endpoints` catalogue can't be read at all -
5
- * no user token, the service principal can't list, or the workspace is
6
- * unreachable - the resolver still has to name *some* endpoint. This
7
- * module holds that floor: a small, hard-coded set of well-known
8
- * Foundation Model API endpoint names, each bucketed into a chat
9
- * {@link ModelClass} by the shared {@link classifyByFamily} heuristic
10
- * (no classes are hard-coded here) and ordered best-first.
11
- *
12
- * This is deliberately *server-only*. A browser client never talks to
13
- * Databricks directly - it always goes through this server - so it has
14
- * nothing to fall back to and must not assume a stale, baked-in model
15
- * list; it consumes the live `/models` response instead. The pure
16
- * classifier ({@link classifyEndpoints}) is what the client shares.
17
- */
18
-
19
- import {
20
- classifyByFamily,
21
- type FamilyClass,
22
- ModelClass,
23
- } from "@dbx-tools/model-shared";
24
-
25
- /**
26
- * Small, last-resort set of well-known Foundation Model API endpoint
27
- * names, ordered best-first within each class by {@link classifyByFamily}.
28
- * Used only as the floor when the live `/serving-endpoints` catalogue
29
- * can't be read at resolve time; the live, score-driven classification
30
- * supersedes it whenever the workspace listing is available. Classes are
31
- * not hard-coded here - each name is classified by family heuristic.
32
- */
33
- const FALLBACK_MODEL_NAMES: readonly string[] = [
34
- "databricks-claude-opus-4-8",
35
- "databricks-gpt-5-5-pro",
36
- "databricks-gemini-3-1-pro",
37
- "databricks-claude-sonnet-4-6",
38
- "databricks-gpt-5-5",
39
- "databricks-meta-llama-3-3-70b-instruct",
40
- "databricks-claude-haiku-4-5",
41
- "databricks-gpt-5-nano",
42
- "databricks-meta-llama-3-1-8b-instruct",
43
- ];
44
-
45
- /**
46
- * Static fallback model ids for a chat class, drawn from the small
47
- * built-in {@link FALLBACK_MODEL_NAMES} list and ordered best-first by
48
- * family rank. Sync and workspace-independent: this is the *fallback
49
- * opinion* used to seed default lists or when the live catalogue is
50
- * unreachable - live resolution prefers `classifyEndpoints`. Returns
51
- * `[]` for {@link ModelClass.Embedding} (the floor is chat-only).
52
- */
53
- export function modelsForClass(cls: ModelClass): readonly string[] {
54
- return FALLBACK_MODEL_NAMES.map((name) => ({ name, c: classifyByFamily(name) }))
55
- .filter(
56
- (x): x is { name: string; c: FamilyClass } => x.c !== null && x.c.class === cls,
57
- )
58
- .sort((a, b) => b.c.rank - a.c.rank)
59
- .map((x) => x.name);
60
- }
61
-
62
- /** Top static fallback model id for a chat class. */
63
- export function modelForClass(cls: ModelClass): string {
64
- return modelsForClass(cls)[0]!;
65
- }
66
-
67
- /**
68
- * Priority-ordered fallback chain (ChatThinking -> ChatBalanced ->
69
- * ChatFast) over the small built-in list. The floor walked at resolve
70
- * time when no agent / plugin / env / request model is set *and* the
71
- * live catalogue yields nothing.
72
- */
73
- export const FALLBACK_MODEL_IDS: readonly string[] = [
74
- ...modelsForClass(ModelClass.ChatThinking),
75
- ...modelsForClass(ModelClass.ChatBalanced),
76
- ...modelsForClass(ModelClass.ChatFast),
77
- ];
package/src/resolve.ts DELETED
@@ -1,303 +0,0 @@
1
- /**
2
- * Workspace-aware model selection.
3
- *
4
- * Given a caller's intent - a search string, a capability
5
- * {@link ModelClass} ceiling, both, or nothing - the toolkit returns
6
- * matching endpoints ranked by match quality then class, or collapses
7
- * to the single best id the workspace actually has, degrading from
8
- * "best in range" down to the static fallback floor. Selection is
9
- * chat-only: embedding endpoints surface only when `modelClass` is
10
- * explicitly {@link ModelClass.Embedding}.
11
- *
12
- * Ranking entry points (return a ranked list):
13
- *
14
- * - {@link rankModels} is the pure ranker over an endpoint list you
15
- * already hold. A chat `modelClass` acts as a ceiling: only that
16
- * band and the less-capable chat bands below it are eligible (see
17
- * {@link classesAtOrBelow}), so a `chat-balanced` ask can fall to
18
- * `chat-fast` but never escalate to `chat-thinking`.
19
- * - {@link searchModels} is the I/O wrapper: hand it a
20
- * `WorkspaceClient` and it lists `/serving-endpoints` (cached) then
21
- * ranks in one step.
22
- *
23
- * Single-selection entry points (return one id + how it was reached):
24
- *
25
- * - {@link resolveModel} is the pure selector; it delegates to
26
- * {@link rankModels} with `limit: 1` and adds the operator-pinned
27
- * fallback / static-floor safety net.
28
- * - {@link selectModel} is the I/O wrapper over {@link resolveModel}.
29
- */
30
-
31
- import {
32
- classifyEndpoints,
33
- ModelClass,
34
- type ModelQuery,
35
- type RankedModel,
36
- type ServingEndpointSummary,
37
- } from "@dbx-tools/model-shared";
38
-
39
- import { CHAT_CLASS_ORDER, classesAtOrBelow, MODEL_CLASS_ORDER } from "./classes.js";
40
- import { FALLBACK_MODEL_IDS, modelsForClass } from "./fallback.js";
41
- import {
42
- listServingEndpoints,
43
- searchServingEndpoints,
44
- type WorkspaceClientLike,
45
- } from "./serving.js";
46
-
47
- /** Caller intent passed to {@link resolveModel}. */
48
- export interface ResolveModelInput {
49
- /**
50
- * Explicit model id / loose name (per-request override, agent /
51
- * plugin default, or env var). When set it wins over `modelClass`
52
- * and `fallbacks`.
53
- */
54
- explicit?: string;
55
- /**
56
- * Fuzzy-match an `explicit` name against the live catalogue so loose
57
- * names like `"claude sonnet"` resolve. Default `true`. When `false`
58
- * the explicit input is returned verbatim (Databricks surfaces the
59
- * canonical 404 if it doesn't exist).
60
- */
61
- fuzzy?: boolean;
62
- /** Fuse.js threshold forwarded to {@link resolveModelId}. */
63
- threshold?: number;
64
- /**
65
- * Chat capability class to resolve when no `explicit` id is given.
66
- * The live catalogue is classified by its Foundation Model API scores
67
- * and the top available model in the class (and the chat bands below
68
- * it) wins, falling back to the class's small static list.
69
- */
70
- modelClass?: ModelClass;
71
- /**
72
- * Operator-supplied fallback ids tried *first* in the no-explicit,
73
- * no-class path (e.g. a regulated workspace pinned to an approved
74
- * subset), ahead of the auto-classified catalogue.
75
- */
76
- fallbacks?: readonly string[];
77
- }
78
-
79
- /** Outcome of {@link resolveModel}: the chosen id plus how it was reached. */
80
- export interface ResolvedModelSelection {
81
- modelId: string;
82
- source: "explicit" | "fuzzy-match" | "class" | "fallback";
83
- }
84
-
85
- /** Intent + catalogue knobs passed to {@link selectModel}. */
86
- export interface SelectModelInput extends ResolveModelInput {
87
- /** TTL override for the cached `/serving-endpoints` listing, in ms. */
88
- ttlMs?: number;
89
- }
90
-
91
- /** TTL override merged into a {@link ModelQuery} for {@link searchModels}. */
92
- export interface SearchModelsInput extends ModelQuery {
93
- /** TTL override for the cached `/serving-endpoints` listing, in ms. */
94
- ttlMs?: number;
95
- }
96
-
97
- /**
98
- * Round a Fuse score to the display precision so version siblings that
99
- * match a token identically (e.g. `opus-4-7` vs `opus-4-8` for the
100
- * query `"opus"`) tie on match and let the class / within-class rank
101
- * decide - which is what surfaces the newer, higher-quality sibling.
102
- */
103
- function matchBucket(score: number | undefined): number {
104
- return Math.round((score ?? 0) * 1000);
105
- }
106
-
107
- /**
108
- * Rank the live catalogue against a {@link ModelQuery}, best-first.
109
- *
110
- * Candidates are the classified endpoints in the eligible classes:
111
- * {@link classesAtOrBelow} the requested `modelClass`, or - when none is
112
- * given - the chat bands only ({@link CHAT_CLASS_ORDER}), so a general
113
- * ask never surfaces an embedding endpoint. Each class bucket is
114
- * already best-first from {@link classifyEndpoints}. Ranking is **match
115
- * then class**:
116
- *
117
- * 1. With a `search`, only endpoints matching it survive, ordered by
118
- * match distance (bucketed via {@link matchBucket} so near-identical
119
- * scores tie), then by class (more capable first), then by the stable
120
- * within-class rank.
121
- * 2. Without a `search`, the class-then-rank candidate order stands.
122
- *
123
- * A `limit` truncates the result. Returns `[]` when nothing is
124
- * eligible or matches - callers layer their own fallback.
125
- */
126
- export function rankModels(
127
- endpoints: readonly ServingEndpointSummary[],
128
- query: ModelQuery = {},
129
- ): RankedModel[] {
130
- const classified = classifyEndpoints(endpoints);
131
- const eligible =
132
- query.modelClass !== undefined
133
- ? classesAtOrBelow(query.modelClass)
134
- : CHAT_CLASS_ORDER;
135
-
136
- // Flatten eligible classes in capability order, carrying each
137
- // endpoint's class; bucket order is already best-first.
138
- const candidates: RankedModel[] = [];
139
- for (const modelClass of eligible) {
140
- for (const endpoint of classified[modelClass])
141
- candidates.push({ endpoint, modelClass });
142
- }
143
-
144
- const search = query.search?.trim();
145
- let ranked: RankedModel[];
146
- if (search) {
147
- const scores = new Map<string, number>();
148
- for (const match of searchServingEndpoints(
149
- search,
150
- candidates.map((c) => c.endpoint),
151
- query.threshold !== undefined ? { threshold: query.threshold } : {},
152
- )) {
153
- scores.set(match.endpoint.name, match.score);
154
- }
155
- // `Array.prototype.sort` is stable, so endpoints equal on match and
156
- // class keep their best-first within-class order.
157
- ranked = candidates
158
- .filter((c) => scores.has(c.endpoint.name))
159
- .map((c) => ({ ...c, score: scores.get(c.endpoint.name) }))
160
- .sort((a, b) => {
161
- const byMatch = matchBucket(a.score) - matchBucket(b.score);
162
- if (byMatch !== 0) return byMatch;
163
- return (
164
- MODEL_CLASS_ORDER.indexOf(a.modelClass) -
165
- MODEL_CLASS_ORDER.indexOf(b.modelClass)
166
- );
167
- });
168
- } else {
169
- ranked = candidates;
170
- }
171
-
172
- return query.limit !== undefined ? ranked.slice(0, Math.max(0, query.limit)) : ranked;
173
- }
174
-
175
- /**
176
- * Rank a workspace's catalogue in one call: list its
177
- * `/serving-endpoints` (cached) and run {@link rankModels} over the
178
- * result. The list counterpart to {@link selectModel}, for a consumer
179
- * that wants the full ranked set (a model picker, a CLI) rather than a
180
- * single id. Catalogue fetches fail loud: network / auth errors
181
- * propagate so the caller sees the real SDK message.
182
- *
183
- * @param host - Workspace host used as the cache key. Pass the value
184
- * resolved from `client.config.getHost()`.
185
- */
186
- export async function searchModels(
187
- client: WorkspaceClientLike,
188
- host: string,
189
- input: SearchModelsInput = {},
190
- ): Promise<RankedModel[]> {
191
- const endpoints = await listServingEndpoints(
192
- client,
193
- host,
194
- input.ttlMs !== undefined ? { ttlMs: input.ttlMs } : {},
195
- );
196
- return rankModels(endpoints, input);
197
- }
198
-
199
- /**
200
- * Resolve a model id for a workspace in one call: list its
201
- * `/serving-endpoints` (cached) and run {@link resolveModel} over the
202
- * result. This is the entry point for any consumer that holds a
203
- * `WorkspaceClient` and just wants a usable model name - a Lakeflow
204
- * job, a one-off script, or the Mastra plugin alike.
205
- *
206
- * Cheap exit: when an `explicit` name is given and `fuzzy` is off, the
207
- * catalogue is never fetched - the name is returned verbatim and
208
- * Databricks surfaces the canonical 404 if it doesn't exist. Catalogue
209
- * fetches otherwise fail loud: network / auth errors propagate so the
210
- * caller sees the real SDK message instead of a silent fallback.
211
- *
212
- * @param host - Workspace host used as the cache key. Pass the value
213
- * resolved from `client.config.getHost()`.
214
- */
215
- export async function selectModel(
216
- client: WorkspaceClientLike,
217
- host: string,
218
- input: SelectModelInput = {},
219
- ): Promise<ResolvedModelSelection> {
220
- if (input.explicit !== undefined && input.fuzzy === false) {
221
- return { modelId: input.explicit, source: "explicit" };
222
- }
223
- const endpoints = await listServingEndpoints(client, host, {
224
- ...(input.ttlMs !== undefined ? { ttlMs: input.ttlMs } : {}),
225
- });
226
- return resolveModel(endpoints, input);
227
- }
228
-
229
- /**
230
- * Resolve a single model id from the live catalogue and caller intent,
231
- * delegating the live selection to {@link rankModels} with `limit: 1`.
232
- *
233
- * 1. **Explicit ask**: with `fuzzy` off, returned verbatim; otherwise
234
- * fuzzy-ranked within the (optional) class ceiling and the best taken,
235
- * falling back to the input verbatim when nothing matches.
236
- * 2. **No explicit ask**: an operator-pinned `fallback` that exists in
237
- * the live catalogue wins first; then the ranked live catalogue
238
- * (class ceiling applied); then the static {@link FALLBACK_MODEL_IDS}
239
- * floor when the catalogue yields nothing in range.
240
- */
241
- export function resolveModel(
242
- endpoints: readonly ServingEndpointSummary[],
243
- input: ResolveModelInput = {},
244
- ): ResolvedModelSelection {
245
- if (input.explicit !== undefined) {
246
- if (input.fuzzy === false) {
247
- return { modelId: input.explicit, source: "explicit" };
248
- }
249
- const [top] = rankModels(endpoints, buildQuery(input, input.explicit));
250
- return { modelId: top?.endpoint.name ?? input.explicit, source: "fuzzy-match" };
251
- }
252
-
253
- // Operator-pinned fallbacks win when present and live (e.g. a
254
- // regulated workspace restricted to an approved subset).
255
- if (input.modelClass === undefined && input.fallbacks && input.fallbacks.length > 0) {
256
- const present = new Set(endpoints.map((e) => e.name));
257
- const pinned = input.fallbacks.find((id) => present.has(id));
258
- if (pinned) return { modelId: pinned, source: "fallback" };
259
- }
260
-
261
- const source = input.modelClass !== undefined ? "class" : "fallback";
262
- const [top] = rankModels(endpoints, buildQuery(input, undefined));
263
- if (top) return { modelId: top.endpoint.name, source };
264
-
265
- // Live catalogue yielded nothing in range: walk the static floor.
266
- const floor =
267
- input.modelClass !== undefined
268
- ? dedupe([...modelsForClass(input.modelClass), ...FALLBACK_MODEL_IDS])
269
- : dedupe([...(input.fallbacks ?? []), ...FALLBACK_MODEL_IDS]);
270
- return { modelId: pickFirstAvailable(floor, endpoints), source };
271
- }
272
-
273
- /** Build a {@link ModelQuery} from {@link ResolveModelInput} for the `limit: 1` delegation. */
274
- function buildQuery(input: ResolveModelInput, search: string | undefined): ModelQuery {
275
- return {
276
- ...(search !== undefined ? { search } : {}),
277
- ...(input.modelClass !== undefined ? { modelClass: input.modelClass } : {}),
278
- ...(input.threshold !== undefined ? { threshold: input.threshold } : {}),
279
- limit: 1,
280
- };
281
- }
282
-
283
- /** Drop duplicate ids while preserving first-seen order. */
284
- function dedupe(ids: readonly string[]): string[] {
285
- return [...new Set(ids)];
286
- }
287
-
288
- /**
289
- * Find the first id in `candidates` whose endpoint is present in
290
- * `endpoints`. Returns the top candidate when the workspace has none
291
- * of them so callers always get a string; an offline workspace then
292
- * receives a clean 404 from Databricks instead of a malformed config.
293
- */
294
- function pickFirstAvailable(
295
- candidates: readonly string[],
296
- endpoints: readonly ServingEndpointSummary[],
297
- ): string {
298
- const present = new Set(endpoints.map((e) => e.name));
299
- for (const candidate of candidates) {
300
- if (present.has(candidate)) return candidate;
301
- }
302
- return candidates[0] ?? FALLBACK_MODEL_IDS[0]!;
303
- }