@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/src/serving.ts DELETED
@@ -1,346 +0,0 @@
1
- /**
2
- * Live Databricks Model Serving catalogue access.
3
- *
4
- * Lists the workspace's `/serving-endpoints` once per host and caches
5
- * the result with a TTL via AppKit's `CacheManager`, with concurrent
6
- * callers sharing one in-flight promise (the coalescing pattern of
7
- * Python's `cachetools-async`). Surfaces each endpoint as a stable
8
- * {@link ServingEndpointSummary} - including the Foundation Model API
9
- * `quality` / `speed` / `cost` profile when present, the classified
10
- * {@link ModelClass}, and (for embedding endpoints) the measured vector
11
- * `dimension` - and snaps loose, human-typed names to real endpoint ids
12
- * through `fuse.js` extended search so tokens like `"claude sonnet"`
13
- * resolve to `databricks-claude-sonnet-4-6`.
14
- *
15
- * The class stamp and embedding dimension are computed once per cache
16
- * load: every embedding endpoint is "pinged" in parallel and the
17
- * resulting vector length recorded, so the cost is paid on a cache miss,
18
- * not per read. The ping is best-effort - a failure logs at debug and
19
- * leaves `dimension` unset rather than failing the whole listing.
20
- */
21
-
22
- import { CacheManager } from "@databricks/appkit";
23
- import {
24
- classifyEndpoints,
25
- ModelClass,
26
- type ModelProfile,
27
- type ServingEndpointSummary,
28
- } from "@dbx-tools/model-shared";
29
- import type { appkitUtils } from "@dbx-tools/shared";
30
- import { commonUtils, logUtils, stringUtils } from "@dbx-tools/shared";
31
- import Fuse from "fuse.js";
32
-
33
- import { MODEL_CLASS_ORDER } from "./classes.js";
34
-
35
- const log = logUtils.logger("model/serving");
36
-
37
- /**
38
- * Structural type for the Databricks workspace client, re-exported from
39
- * `@dbx-tools/shared` so the rest of this package can keep importing it
40
- * from here. See `appkitUtils.WorkspaceClientLike` for the canonical
41
- * definition.
42
- */
43
- export type WorkspaceClientLike = appkitUtils.WorkspaceClientLike;
44
-
45
- /** Default TTL for the in-memory endpoint cache. Matches the Databricks SDK's session lifetime budget. */
46
- export const DEFAULT_MODEL_CACHE_TTL_MS = 5 * 60 * 1000;
47
-
48
- /** Default Fuse.js score threshold below which a fuzzy match is accepted. */
49
- export const DEFAULT_FUZZY_THRESHOLD = 0.4;
50
-
51
- /** Cache key parts under which endpoint listings are stored. */
52
- const CACHE_KEY_NAMESPACE = "serving-endpoints";
53
-
54
- /**
55
- * Stable `userKey` arg for AppKit's `CacheManager.getOrExecute`.
56
- * Endpoint visibility is effectively workspace-scoped (we cache by
57
- * host in the key parts), so a single shared key lets every user of
58
- * the same workspace share one cached fetch and coalesce on the
59
- * in-flight promise. Permissions can differ in theory, but the
60
- * Foundation Model API catalogue is the same view for every caller.
61
- */
62
- const SHARED_USER_KEY = "model-shared";
63
-
64
- /** Options for {@link listServingEndpoints}. */
65
- export interface ListServingEndpointsOptions {
66
- /**
67
- * Override the default cache TTL for this call, in milliseconds.
68
- * Forwarded to `CacheManager` as seconds.
69
- */
70
- ttlMs?: number;
71
- }
72
-
73
- /**
74
- * List Model Serving endpoints for the workspace owning `client`,
75
- * routed through AppKit's `CacheManager`. The manager gives us
76
- * everything `cachetools.TTLCache` provides plus what
77
- * `cachetools-async` adds on top: per-entry TTL, in-flight request
78
- * coalescing (concurrent callers share one fetch via the manager's
79
- * internal `inFlightRequests` map), bounded size, telemetry spans
80
- * (`cache.getOrExecute`), and optional Lakebase persistence so the
81
- * catalogue survives restarts when the lakebase plugin is wired up.
82
- *
83
- * Returns plain {@link ServingEndpointSummary} objects (a stable
84
- * subset of the SDK type) so cache hits never expose stale SDK
85
- * internals. Errors from `CacheManager` or the SDK fetch propagate
86
- * to the caller - we don't swallow them so users see the real
87
- * auth / network issue.
88
- *
89
- * @param host - Workspace host used as the cache key. Pass the value
90
- * resolved from `client.config.getHost()` so multi-host apps share
91
- * one entry per workspace.
92
- * @param options.ttlMs - Override the default TTL just for this call.
93
- * Forwarded to `CacheManager` as seconds.
94
- */
95
- export async function listServingEndpoints(
96
- client: WorkspaceClientLike,
97
- host: string,
98
- options: ListServingEndpointsOptions = {},
99
- ): Promise<ServingEndpointSummary[]> {
100
- const ttlSec = Math.max(
101
- 1,
102
- Math.round((options.ttlMs ?? DEFAULT_MODEL_CACHE_TTL_MS) / 1000),
103
- );
104
- return CacheManager.getInstanceSync().getOrExecute(
105
- [CACHE_KEY_NAMESPACE, host],
106
- () => fetchEndpoints(client),
107
- SHARED_USER_KEY,
108
- { ttl: ttlSec },
109
- );
110
- }
111
-
112
- async function fetchEndpoints(
113
- client: WorkspaceClientLike,
114
- ): Promise<ServingEndpointSummary[]> {
115
- const startedAt = Date.now();
116
- const out: ServingEndpointSummary[] = [];
117
- for await (const ep of client.servingEndpoints.list()) {
118
- if (!ep.name) continue;
119
- const profile = extractProfile(ep);
120
- out.push({
121
- name: ep.name,
122
- ...(ep.task !== undefined ? { task: ep.task } : {}),
123
- ...(ep.state?.ready !== undefined ? { state: String(ep.state.ready) } : {}),
124
- ...(ep.description !== undefined ? { description: ep.description } : {}),
125
- ...(profile ? { profile } : {}),
126
- });
127
- }
128
- stampModelClasses(out);
129
- await measureEmbeddingDimensions(client, out);
130
- log.debug("listed", { count: out.length, elapsedMs: Date.now() - startedAt });
131
- return out;
132
- }
133
-
134
- /**
135
- * Stamp each summary's {@link ServingEndpointSummary.class} from the
136
- * relative classification of the whole set. Mutates `summaries` in
137
- * place. Endpoints the classifier doesn't recognize (custom, unscored,
138
- * non-LLM) are left without a class.
139
- */
140
- function stampModelClasses(summaries: ServingEndpointSummary[]): void {
141
- const buckets = classifyEndpoints(summaries);
142
- const classOf = new Map<string, ModelClass>();
143
- for (const cls of MODEL_CLASS_ORDER) {
144
- for (const ep of buckets[cls]) classOf.set(ep.name, cls);
145
- }
146
- for (const summary of summaries) {
147
- const cls = classOf.get(summary.name);
148
- if (cls !== undefined) summary.class = cls;
149
- }
150
- }
151
-
152
- /**
153
- * Measure the embedding vector dimension of every
154
- * {@link ModelClass.Embedding} endpoint by pinging it once, all in
155
- * parallel. Mutates the matching summaries in place with the resulting
156
- * `dimension`. Runs only on a cache miss (it's called from
157
- * {@link fetchEndpoints}), so the probe cost is amortized across the
158
- * cached TTL window. Per-endpoint failures are swallowed (logged at
159
- * warn) so one unreachable embedding model never fails the listing.
160
- */
161
- async function measureEmbeddingDimensions(
162
- client: WorkspaceClientLike,
163
- summaries: ServingEndpointSummary[],
164
- ): Promise<void> {
165
- await Promise.all(
166
- summaries
167
- .filter((s) => s.class === ModelClass.Embedding)
168
- .map(async (summary) => {
169
- const dimension = await pingEmbeddingDimension(client, summary.name);
170
- if (dimension !== undefined) summary.dimension = dimension;
171
- }),
172
- );
173
- }
174
-
175
- /**
176
- * Best-effort embedding dimension probe: query `name` with a tiny
177
- * `"ping"` input and return the length of the returned vector. Returns
178
- * `undefined` (and logs at warn) when the endpoint can't be queried or
179
- * returns no vector - the dimension is informational, never required.
180
- */
181
- async function pingEmbeddingDimension(
182
- client: WorkspaceClientLike,
183
- name: string,
184
- ): Promise<number | undefined> {
185
- try {
186
- const response = await client.servingEndpoints.query({ name, input: "ping" });
187
- const dimension = response.data?.[0]?.embedding?.length;
188
- if (typeof dimension === "number" && dimension > 0) return dimension;
189
- log.warn("embedding ping returned no vector", { name });
190
- return undefined;
191
- } catch (err) {
192
- log.warn("embedding ping failed", { name, error: commonUtils.errorMessage(err) });
193
- return undefined;
194
- }
195
- }
196
-
197
- /**
198
- * Pull the Foundation Model API `quality` / `speed` / `cost` scores
199
- * off a serving-endpoint listing entry. Databricks returns these
200
- * under `config.served_entities[].foundation_model.ai_gateway_model_profile`
201
- * (snake_case at the wire level, preserved verbatim by the SDK), but
202
- * the field is newer than the typed `FoundationModel` interface, so we
203
- * read it through a structural cast. Returns `undefined` when no
204
- * served entity carries a profile (custom models, embeddings, and
205
- * brand-new endpoints that Databricks has not scored yet).
206
- */
207
- function extractProfile(ep: unknown): ModelProfile | undefined {
208
- const entities = (
209
- ep as {
210
- config?: {
211
- served_entities?: Array<{
212
- foundation_model?: {
213
- ai_gateway_model_profile?: {
214
- quality?: number;
215
- speed?: number;
216
- cost?: number;
217
- };
218
- };
219
- }>;
220
- };
221
- }
222
- ).config?.served_entities;
223
- if (!entities) return undefined;
224
- for (const entity of entities) {
225
- const raw = entity.foundation_model?.ai_gateway_model_profile;
226
- if (!raw) continue;
227
- const profile: ModelProfile = {};
228
- if (Number.isFinite(raw.quality)) profile.quality = raw.quality;
229
- if (Number.isFinite(raw.speed)) profile.speed = raw.speed;
230
- if (Number.isFinite(raw.cost)) profile.cost = raw.cost;
231
- if (Object.keys(profile).length > 0) return profile;
232
- }
233
- return undefined;
234
- }
235
-
236
- /**
237
- * Force-evict cached endpoint listings via AppKit's `CacheManager`.
238
- * With a `host` deletes that one workspace's entry; without one
239
- * clears every cache entry on the manager (since `CacheManager`
240
- * doesn't expose a namespace-scoped clear, this is the brute-force
241
- * path - fine for tests, avoid in steady-state code).
242
- */
243
- export async function clearServingEndpointsCache(host?: string): Promise<void> {
244
- const cache = CacheManager.getInstanceSync();
245
- if (host) {
246
- const key = cache.generateKey([CACHE_KEY_NAMESPACE, host], SHARED_USER_KEY);
247
- await cache.delete(key);
248
- } else {
249
- await cache.clear();
250
- }
251
- }
252
-
253
- /**
254
- * Result of fuzzy-resolving a user-supplied model name against the
255
- * live endpoint list. `score` is Fuse.js's distance (`0` is exact,
256
- * `1` is no match); `matched` is `false` when the score exceeds the
257
- * configured threshold so callers can fall back to the original
258
- * input (Databricks will then return a clean 404).
259
- */
260
- export interface ResolvedModel {
261
- modelId: string;
262
- matched: boolean;
263
- score?: number;
264
- }
265
-
266
- /** Options accepted by {@link resolveModelId} / {@link searchServingEndpoints}. */
267
- export interface ResolveModelOptions {
268
- /** Fuse.js threshold (0 = exact, 1 = anything). Default `0.4`. */
269
- threshold?: number;
270
- }
271
-
272
- /** A serving endpoint paired with its fuzzy-match distance for a query. */
273
- export interface ScoredEndpoint {
274
- endpoint: ServingEndpointSummary;
275
- /** Fuse.js distance: `0` is exact, `1` is no match. */
276
- score: number;
277
- }
278
-
279
- /**
280
- * Fuzzy-rank endpoints by how closely their `name` matches `input`,
281
- * best (lowest score) first, keeping only those within `threshold`:
282
- *
283
- * 1. An exact name match short-circuits to a single `score: 0` result.
284
- * 2. Otherwise the input is tokenized (dashes / underscores / spaces
285
- * become separators) and fed through Fuse.js extended search, which
286
- * AND-s each token with fuzzy matching enabled - the "tokenized
287
- * fuzzy match" a caller reaches for when they type `"claude sonnet"`
288
- * instead of the full endpoint name.
289
- *
290
- * Returns `[]` for an empty endpoint list or when `input` tokenizes to
291
- * nothing, so callers fall back to the raw input and let Databricks
292
- * surface a clean 404. This multi-result core is shared by
293
- * {@link resolveModelId} (single best) and the ranked `rankModels`
294
- * selector.
295
- */
296
- export function searchServingEndpoints(
297
- input: string,
298
- endpoints: readonly ServingEndpointSummary[],
299
- options: ResolveModelOptions = {},
300
- ): ScoredEndpoint[] {
301
- if (endpoints.length === 0) return [];
302
- for (const ep of endpoints) {
303
- if (ep.name === input) return [{ endpoint: ep, score: 0 }];
304
- }
305
- const threshold = options.threshold ?? DEFAULT_FUZZY_THRESHOLD;
306
- // Fuse 7.3 has no built-in tokenize hook; in extended search,
307
- // space-separated tokens are AND-ed with fuzzy matching enabled. We
308
- // lean on the shared tokenizer so the splitting rules stay
309
- // consistent with the rest of the toolkit.
310
- const query = Array.from(
311
- stringUtils.tokenizeWithOptions({ lowerCase: true, camelCase: false }, input),
312
- ).join(" ");
313
- if (!query) return [];
314
- const fuse = new Fuse(endpoints, {
315
- keys: ["name"],
316
- threshold,
317
- ignoreLocation: true,
318
- includeScore: true,
319
- useExtendedSearch: true,
320
- isCaseSensitive: false,
321
- });
322
- return fuse
323
- .search(query)
324
- .filter((r) => (r.score ?? 0) <= threshold)
325
- .map((r) => ({ endpoint: r.item, score: r.score ?? 0 }));
326
- }
327
-
328
- /**
329
- * Snap a user-supplied model name to the single closest configured
330
- * serving endpoint via {@link searchServingEndpoints}. Returns the
331
- * input unchanged with `matched: false` when nothing scores within the
332
- * threshold (or the catalogue is empty), so a deliberate model id is
333
- * never silently rewritten to a similar-looking neighbour and the
334
- * upstream call surfaces the canonical 404.
335
- */
336
- export function resolveModelId(
337
- input: string,
338
- endpoints: readonly ServingEndpointSummary[],
339
- options: ResolveModelOptions = {},
340
- ): ResolvedModel {
341
- const [best] = searchServingEndpoints(input, endpoints, options);
342
- if (best) {
343
- return { modelId: best.endpoint.name, matched: true, score: best.score };
344
- }
345
- return { modelId: input, matched: false };
346
- }