@abhishek944/pi-embeddings 0.1.0 → 0.4.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 +59 -9
- package/dist/execute.js +56 -3
- package/dist/extension.js +8 -39
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/mcp-server.js +1 -14
- package/dist/providers.d.ts +13 -2
- package/dist/providers.js +263 -3
- package/dist/response.d.ts +21 -0
- package/dist/response.js +115 -0
- package/dist/runtime.d.ts +22 -2
- package/dist/runtime.js +12 -3
- package/dist/schemas.d.ts +703 -81
- package/dist/schemas.js +137 -16
- package/dist/settings-write.js +2 -2
- package/dist/settings.js +8 -1
- package/dist/tool-contracts.d.ts +459 -184
- package/dist/tool-contracts.js +2 -11
- package/dist/vertex-provider.d.ts +18 -0
- package/dist/vertex-provider.js +139 -0
- package/package.json +9 -2
- package/src/execute.ts +59 -3
- package/src/extension.ts +12 -47
- package/src/index.ts +11 -2
- package/src/mcp-server.ts +0 -19
- package/src/providers.ts +322 -3
- package/src/response.ts +135 -0
- package/src/runtime.ts +44 -6
- package/src/schemas.ts +180 -26
- package/src/settings-write.ts +2 -2
- package/src/settings.ts +10 -0
- package/src/tool-contracts.ts +1 -13
- package/src/vertex-provider.ts +152 -0
package/dist/providers.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { getEncoding } from 'js-tiktoken';
|
|
2
|
+
import { VertexProvider, vertexEmbeddingSpace } from './vertex-provider.js';
|
|
2
3
|
import { EmbeddingsError } from './errors.js';
|
|
3
|
-
import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, } from './schemas.js';
|
|
4
|
+
import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, GEMINI_EMBEDDING_MODELS, GEMINI_TASK_PREFIXES, OPENROUTER_EMBEDDING_MODELS, } from './schemas.js';
|
|
4
5
|
import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
|
|
5
6
|
import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
|
|
6
|
-
import { parseBatchResponse } from './response.js';
|
|
7
|
+
import { parseBatchResponse, parseCloudflareBatchResponse, parseGeminiCountTokensResponse, parseGeminiEmbeddingResponse, } from './response.js';
|
|
7
8
|
export const OPENAI_EMBEDDING_SPACE = Object.freeze({
|
|
8
9
|
provider: 'openai',
|
|
9
10
|
model: 'text-embedding-3-small',
|
|
@@ -26,9 +27,37 @@ export const SARVAM_EMBEDDING_SPACE = Object.freeze({
|
|
|
26
27
|
prefix: EMBEDDING_DOCUMENT_PREFIX,
|
|
27
28
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
28
29
|
});
|
|
30
|
+
export const cloudflareEmbeddingSpace = (pooling) => Object.freeze({
|
|
31
|
+
provider: 'cloudflare',
|
|
32
|
+
model: CLOUDFLARE_EMBEDDING_MODELS[0],
|
|
33
|
+
revision: null,
|
|
34
|
+
quantization: null,
|
|
35
|
+
runtime: 'cloudflare-workers-ai',
|
|
36
|
+
dimensions: 768,
|
|
37
|
+
pooling,
|
|
38
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
39
|
+
prefix: EMBEDDING_DOCUMENT_PREFIX,
|
|
40
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
41
|
+
});
|
|
42
|
+
export const geminiEmbeddingSpace = (config) => Object.freeze({
|
|
43
|
+
provider: 'gemini',
|
|
44
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
45
|
+
revision: null,
|
|
46
|
+
quantization: null,
|
|
47
|
+
runtime: 'gemini-api-v1beta',
|
|
48
|
+
dimensions: config.dimensions,
|
|
49
|
+
taskFormat: config.taskFormat,
|
|
50
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
51
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
52
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
53
|
+
});
|
|
29
54
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
30
55
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
31
56
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
57
|
+
const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
|
|
58
|
+
const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
|
|
59
|
+
const GEMINI_ORIGIN = 'https://generativelanguage.googleapis.com';
|
|
60
|
+
const GEMINI_MAX_INPUT_TOKENS = 8192;
|
|
32
61
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
33
62
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
34
63
|
const OPENAI_MAX_REQUEST_TOKENS = 300000;
|
|
@@ -66,6 +95,29 @@ export function routeDiagnostics(settings, route) {
|
|
|
66
95
|
add('gateway-key-unconfigured');
|
|
67
96
|
break;
|
|
68
97
|
}
|
|
98
|
+
case 'openrouter':
|
|
99
|
+
if (trim(settings.providers?.openrouter?.apiKey) === undefined && trim(process.env.OPENROUTER_API_KEY) === undefined)
|
|
100
|
+
add('openrouter-key-unconfigured');
|
|
101
|
+
break;
|
|
102
|
+
case 'cloudflare': {
|
|
103
|
+
const cloudflare = settings.providers?.cloudflare;
|
|
104
|
+
if (trim(cloudflare?.accountId) === undefined && trim(process.env.CLOUDFLARE_ACCOUNT_ID) === undefined)
|
|
105
|
+
add('cloudflare-account-unconfigured');
|
|
106
|
+
if (trim(cloudflare?.apiKey) === undefined && trim(process.env.CLOUDFLARE_API_TOKEN) === undefined)
|
|
107
|
+
add('cloudflare-key-unconfigured');
|
|
108
|
+
if (trim(cloudflare?.gatewayId) === undefined && trim(process.env.CLOUDFLARE_AI_GATEWAY_ID) === undefined)
|
|
109
|
+
add('cloudflare-gateway-unconfigured');
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
case 'gemini':
|
|
113
|
+
if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
|
|
114
|
+
add('gemini-key-unconfigured');
|
|
115
|
+
break;
|
|
116
|
+
case 'vertex':
|
|
117
|
+
if (settings.providers?.vertex === undefined)
|
|
118
|
+
add('vertex-configuration-unconfigured');
|
|
119
|
+
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
120
|
+
break;
|
|
69
121
|
}
|
|
70
122
|
return diagnostics;
|
|
71
123
|
}
|
|
@@ -75,6 +127,12 @@ const credential = (configured, env) => {
|
|
|
75
127
|
throw new EmbeddingsError('missing-credentials');
|
|
76
128
|
return value;
|
|
77
129
|
};
|
|
130
|
+
const headerCredential = (configured, env) => {
|
|
131
|
+
const value = credential(configured, env);
|
|
132
|
+
if (!headerValueIsSafe(value))
|
|
133
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
134
|
+
return value;
|
|
135
|
+
};
|
|
78
136
|
/** The documented text-string path avoids the token-array schema contradiction without truncating. */
|
|
79
137
|
const openAIPrepare = (encoding, text, signal) => {
|
|
80
138
|
signal.throwIfAborted();
|
|
@@ -210,6 +268,150 @@ class GatewayProvider {
|
|
|
210
268
|
// js-tiktoken is pure JavaScript and owns no process or handle.
|
|
211
269
|
}
|
|
212
270
|
}
|
|
271
|
+
class OpenRouterProvider {
|
|
272
|
+
route = 'openrouter';
|
|
273
|
+
model = OPENROUTER_EMBEDDING_MODELS[0];
|
|
274
|
+
space = OPENAI_EMBEDDING_SPACE;
|
|
275
|
+
maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
|
|
276
|
+
maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
|
|
277
|
+
#encoding = getEncoding('cl100k_base');
|
|
278
|
+
#key;
|
|
279
|
+
constructor(key) {
|
|
280
|
+
this.#key = key;
|
|
281
|
+
}
|
|
282
|
+
async prepare(text, signal) {
|
|
283
|
+
return openAIPrepare(this.#encoding, text, signal);
|
|
284
|
+
}
|
|
285
|
+
async embed(inputs, signal) {
|
|
286
|
+
const response = await requestJson({
|
|
287
|
+
url: new URL(OPENROUTER_EMBEDDINGS_URL),
|
|
288
|
+
signal,
|
|
289
|
+
headers: { authorization: `Bearer ${this.#key}` },
|
|
290
|
+
body: {
|
|
291
|
+
model: this.model,
|
|
292
|
+
dimensions: this.space.dimensions,
|
|
293
|
+
input: providerTexts(inputs),
|
|
294
|
+
encoding_format: 'float',
|
|
295
|
+
},
|
|
296
|
+
});
|
|
297
|
+
const count = preparedTokens(inputs);
|
|
298
|
+
return parseBatchResponse({
|
|
299
|
+
response,
|
|
300
|
+
space: this.space,
|
|
301
|
+
expectedModels: [this.model],
|
|
302
|
+
expectedPreparedTokens: count,
|
|
303
|
+
preparedInputTokens: count,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
async close() {
|
|
307
|
+
// js-tiktoken is pure JavaScript and owns no process or handle.
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
class CloudflareProvider {
|
|
311
|
+
route = 'cloudflare';
|
|
312
|
+
model = CLOUDFLARE_EMBEDDING_MODELS[0];
|
|
313
|
+
space;
|
|
314
|
+
// Workers AI documents a 512-token input ceiling for this model but no aggregate request cap.
|
|
315
|
+
// The model-owned tokenizer is not available here, so no approximate local cap is invented.
|
|
316
|
+
maxRequestInputs = Number.POSITIVE_INFINITY;
|
|
317
|
+
maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
318
|
+
#url;
|
|
319
|
+
#key;
|
|
320
|
+
#gatewayId;
|
|
321
|
+
#pooling;
|
|
322
|
+
constructor(config) {
|
|
323
|
+
this.#url = new URL(`${CLOUDFLARE_ORIGIN}/${encodeURIComponent(config.accountId)}/ai/run/${config.model}`);
|
|
324
|
+
this.#key = config.apiKey;
|
|
325
|
+
this.#gatewayId = config.gatewayId;
|
|
326
|
+
this.#pooling = config.pooling;
|
|
327
|
+
this.space = cloudflareEmbeddingSpace(config.pooling);
|
|
328
|
+
// The model is pinned from settings; this guard keeps the fixed URL invariant explicit.
|
|
329
|
+
if (config.model !== CLOUDFLARE_EMBEDDING_MODELS[0])
|
|
330
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
331
|
+
}
|
|
332
|
+
async prepare(text, signal) {
|
|
333
|
+
signal.throwIfAborted();
|
|
334
|
+
return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
|
|
335
|
+
}
|
|
336
|
+
async embed(inputs, signal) {
|
|
337
|
+
const response = await requestJson({
|
|
338
|
+
url: this.#url,
|
|
339
|
+
signal,
|
|
340
|
+
headers: {
|
|
341
|
+
authorization: `Bearer ${this.#key}`,
|
|
342
|
+
'cf-aig-gateway-id': this.#gatewayId,
|
|
343
|
+
},
|
|
344
|
+
body: { text: providerTexts(inputs), pooling: this.#pooling },
|
|
345
|
+
});
|
|
346
|
+
return parseCloudflareBatchResponse({
|
|
347
|
+
response,
|
|
348
|
+
space: this.space,
|
|
349
|
+
expectedCount: inputs.length,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
async close() {
|
|
353
|
+
// Native fetch owns no long-lived resource.
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
class GeminiProvider {
|
|
357
|
+
route = 'gemini';
|
|
358
|
+
model = GEMINI_EMBEDDING_MODELS[0];
|
|
359
|
+
space;
|
|
360
|
+
// One exact prepared prompt is counted and embedded per request; no vector is accepted unless the
|
|
361
|
+
// embed response token count equals that preflight count.
|
|
362
|
+
maxRequestInputs = 1;
|
|
363
|
+
maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
364
|
+
#url = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:embedContent`, GEMINI_ORIGIN);
|
|
365
|
+
#countUrl = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:countTokens`, GEMINI_ORIGIN);
|
|
366
|
+
#key;
|
|
367
|
+
#taskFormat;
|
|
368
|
+
constructor(key, config) {
|
|
369
|
+
this.#key = key;
|
|
370
|
+
this.#taskFormat = config.taskFormat;
|
|
371
|
+
this.space = geminiEmbeddingSpace(config);
|
|
372
|
+
}
|
|
373
|
+
async prepare(text, signal) {
|
|
374
|
+
signal.throwIfAborted();
|
|
375
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#taskFormat] + text;
|
|
376
|
+
const response = await requestJson({
|
|
377
|
+
url: this.#countUrl,
|
|
378
|
+
signal,
|
|
379
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
380
|
+
body: { contents: [{ parts: [{ text: prepared }] }] },
|
|
381
|
+
});
|
|
382
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
383
|
+
if (tokenCount > GEMINI_MAX_INPUT_TOKENS)
|
|
384
|
+
throw new EmbeddingsError('input-too-long', {
|
|
385
|
+
knownUsage: { preparedInputTokens: tokenCount },
|
|
386
|
+
});
|
|
387
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
388
|
+
}
|
|
389
|
+
async embed(inputs, signal) {
|
|
390
|
+
const text = providerTexts(inputs)[0];
|
|
391
|
+
if (inputs.length !== 1 || text === undefined)
|
|
392
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
393
|
+
const preparedInputTokens = preparedTokens(inputs);
|
|
394
|
+
const response = await requestJson({
|
|
395
|
+
url: this.#url,
|
|
396
|
+
signal,
|
|
397
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
398
|
+
body: {
|
|
399
|
+
model: `models/${this.model}`,
|
|
400
|
+
content: { parts: [{ text }] },
|
|
401
|
+
output_dimensionality: this.space.dimensions,
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
return parseGeminiEmbeddingResponse({
|
|
405
|
+
response,
|
|
406
|
+
space: this.space,
|
|
407
|
+
maxInputTokens: GEMINI_MAX_INPUT_TOKENS,
|
|
408
|
+
preparedInputTokens,
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
async close() {
|
|
412
|
+
// Native fetch owns no long-lived resource.
|
|
413
|
+
}
|
|
414
|
+
}
|
|
213
415
|
const noRelease = async () => undefined;
|
|
214
416
|
/** Resolve a configured route only when that route is actually about to be used. */
|
|
215
417
|
export async function acquireProvider({ settings, route, signal, }) {
|
|
@@ -250,16 +452,74 @@ export async function acquireProvider({ settings, route, signal, }) {
|
|
|
250
452
|
release: noRelease,
|
|
251
453
|
};
|
|
252
454
|
}
|
|
455
|
+
case 'openrouter':
|
|
456
|
+
return {
|
|
457
|
+
provider: new OpenRouterProvider(headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)),
|
|
458
|
+
release: noRelease,
|
|
459
|
+
};
|
|
460
|
+
case 'cloudflare': {
|
|
461
|
+
const configured = settings.providers?.cloudflare;
|
|
462
|
+
const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
|
|
463
|
+
const gatewayId = trim(configured?.gatewayId) ?? trim(process.env.CLOUDFLARE_AI_GATEWAY_ID);
|
|
464
|
+
if (accountId === undefined || gatewayId === undefined)
|
|
465
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
466
|
+
if (!headerValueIsSafe(accountId) || !headerValueIsSafe(gatewayId))
|
|
467
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
468
|
+
const model = trim(configured?.model) ?? CLOUDFLARE_EMBEDDING_MODELS[0];
|
|
469
|
+
if (model !== CLOUDFLARE_EMBEDDING_MODELS[0])
|
|
470
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
471
|
+
const pooling = configured?.pooling ?? 'mean';
|
|
472
|
+
return {
|
|
473
|
+
provider: new CloudflareProvider({
|
|
474
|
+
accountId,
|
|
475
|
+
apiKey: headerCredential(configured?.apiKey, process.env.CLOUDFLARE_API_TOKEN),
|
|
476
|
+
gatewayId,
|
|
477
|
+
model,
|
|
478
|
+
pooling,
|
|
479
|
+
}),
|
|
480
|
+
release: noRelease,
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
case 'vertex': {
|
|
484
|
+
const configured = settings.providers?.vertex;
|
|
485
|
+
if (configured === undefined)
|
|
486
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
487
|
+
return { provider: new VertexProvider(configured), release: noRelease };
|
|
488
|
+
}
|
|
489
|
+
case 'gemini': {
|
|
490
|
+
const configured = settings.providers?.gemini;
|
|
491
|
+
return {
|
|
492
|
+
provider: new GeminiProvider(headerCredential(configured?.apiKey, process.env.GEMINI_API_KEY), {
|
|
493
|
+
dimensions: configured?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
494
|
+
taskFormat: configured?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
495
|
+
}),
|
|
496
|
+
release: noRelease,
|
|
497
|
+
};
|
|
498
|
+
}
|
|
253
499
|
}
|
|
254
500
|
}
|
|
255
|
-
export const spaceForRoute = (route) => {
|
|
501
|
+
export const spaceForRoute = (route, settings) => {
|
|
256
502
|
switch (route.provider) {
|
|
257
503
|
case 'local':
|
|
258
504
|
return LOCAL_EMBEDDING_SPACE;
|
|
259
505
|
case 'openai':
|
|
260
506
|
case 'gateway':
|
|
507
|
+
case 'openrouter':
|
|
261
508
|
return OPENAI_EMBEDDING_SPACE;
|
|
262
509
|
case 'sarvam':
|
|
263
510
|
return SARVAM_EMBEDDING_SPACE;
|
|
511
|
+
case 'cloudflare':
|
|
512
|
+
return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
|
|
513
|
+
case 'vertex': {
|
|
514
|
+
const configured = settings?.providers?.vertex;
|
|
515
|
+
if (configured === undefined)
|
|
516
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
517
|
+
return vertexEmbeddingSpace(configured);
|
|
518
|
+
}
|
|
519
|
+
case 'gemini':
|
|
520
|
+
return geminiEmbeddingSpace({
|
|
521
|
+
dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
522
|
+
taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
523
|
+
});
|
|
264
524
|
}
|
|
265
525
|
};
|
package/dist/response.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { ProviderBatchResult } from './provider-types.js';
|
|
2
2
|
import type { EmbeddingSpace } from './schemas.js';
|
|
3
|
+
/** Exact prepared-prompt count from the model's own tokenizer, used before inference. */
|
|
4
|
+
export declare function parseGeminiCountTokensResponse(response: unknown): number;
|
|
3
5
|
/** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
|
|
4
6
|
export declare function normalizeVector(vector: readonly number[], dimensions: number): number[];
|
|
5
7
|
export declare function parseBatchResponse(args: {
|
|
@@ -9,3 +11,22 @@ export declare function parseBatchResponse(args: {
|
|
|
9
11
|
expectedPreparedTokens?: number | null;
|
|
10
12
|
preparedInputTokens?: number | null;
|
|
11
13
|
}): ProviderBatchResult;
|
|
14
|
+
/**
|
|
15
|
+
* Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
|
|
16
|
+
* only when that response count matches the exact prepared prompt counted before inference; a mismatch
|
|
17
|
+
* or over-limit count fails closed instead of relying on undocumented truncation semantics.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseGeminiEmbeddingResponse(args: {
|
|
20
|
+
response: unknown;
|
|
21
|
+
space: EmbeddingSpace;
|
|
22
|
+
maxInputTokens: number;
|
|
23
|
+
preparedInputTokens: number;
|
|
24
|
+
}): ProviderBatchResult;
|
|
25
|
+
/** Vertex's explicit truncation flag is checked in addition to the exact preflight token count. */
|
|
26
|
+
export declare function parseVertexEmbeddingResponse(args: Parameters<typeof parseGeminiEmbeddingResponse>[0]): ProviderBatchResult;
|
|
27
|
+
/** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
|
|
28
|
+
export declare function parseCloudflareBatchResponse(args: {
|
|
29
|
+
response: unknown;
|
|
30
|
+
space: EmbeddingSpace;
|
|
31
|
+
expectedCount: number;
|
|
32
|
+
}): ProviderBatchResult;
|
package/dist/response.js
CHANGED
|
@@ -11,6 +11,38 @@ const responseSchema = Type.Object({
|
|
|
11
11
|
prompt_tokens: Type.Integer({ minimum: 0 }),
|
|
12
12
|
}),
|
|
13
13
|
});
|
|
14
|
+
const cloudflareResponseSchema = Type.Object({
|
|
15
|
+
shape: Type.Optional(Type.Array(Type.Integer({ minimum: 0 }))),
|
|
16
|
+
data: Type.Array(Type.Array(Type.Number())),
|
|
17
|
+
pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
|
|
18
|
+
});
|
|
19
|
+
const geminiEmbeddingResponseSchema = Type.Object({
|
|
20
|
+
embedding: Type.Object({ values: Type.Array(Type.Number()) }),
|
|
21
|
+
usageMetadata: Type.Object({ promptTokenCount: Type.Integer({ minimum: 0 }) }),
|
|
22
|
+
});
|
|
23
|
+
const vertexEmbeddingResponseSchema = Type.Object({
|
|
24
|
+
...geminiEmbeddingResponseSchema.properties,
|
|
25
|
+
truncated: Type.Optional(Type.Boolean()),
|
|
26
|
+
});
|
|
27
|
+
const geminiCountTokensResponseSchema = Type.Object({
|
|
28
|
+
totalTokens: Type.Integer({ minimum: 0 }),
|
|
29
|
+
});
|
|
30
|
+
/** Exact prepared-prompt count from the model's own tokenizer, used before inference. */
|
|
31
|
+
export function parseGeminiCountTokensResponse(response) {
|
|
32
|
+
if (!Value.Check(geminiCountTokensResponseSchema, response))
|
|
33
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
34
|
+
return response.totalTokens;
|
|
35
|
+
}
|
|
36
|
+
/** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
|
|
37
|
+
function unwrapCloudflareModelOutput(response) {
|
|
38
|
+
if (typeof response !== 'object' || response === null || Array.isArray(response))
|
|
39
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
40
|
+
const envelope = response;
|
|
41
|
+
if (envelope.success === false ||
|
|
42
|
+
(Array.isArray(envelope.errors) && envelope.errors.length > 0))
|
|
43
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
44
|
+
return Object.hasOwn(envelope, 'result') ? envelope.result : envelope;
|
|
45
|
+
}
|
|
14
46
|
/** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
|
|
15
47
|
export function normalizeVector(vector, dimensions) {
|
|
16
48
|
if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
|
|
@@ -60,3 +92,86 @@ export function parseBatchResponse(args) {
|
|
|
60
92
|
},
|
|
61
93
|
};
|
|
62
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
|
|
97
|
+
* only when that response count matches the exact prepared prompt counted before inference; a mismatch
|
|
98
|
+
* or over-limit count fails closed instead of relying on undocumented truncation semantics.
|
|
99
|
+
*/
|
|
100
|
+
export function parseGeminiEmbeddingResponse(args) {
|
|
101
|
+
if (!Value.Check(geminiEmbeddingResponseSchema, args.response))
|
|
102
|
+
throw new EmbeddingsError('provider-response-invalid', {
|
|
103
|
+
knownUsage: { preparedInputTokens: args.preparedInputTokens },
|
|
104
|
+
});
|
|
105
|
+
const parsed = args.response;
|
|
106
|
+
const promptTokens = parsed.usageMetadata.promptTokenCount;
|
|
107
|
+
const knownUsage = {
|
|
108
|
+
providerReportedInputTokens: promptTokens,
|
|
109
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
110
|
+
};
|
|
111
|
+
if (promptTokens !== args.preparedInputTokens)
|
|
112
|
+
throw new EmbeddingsError('provider-response-mismatch', { knownUsage });
|
|
113
|
+
if (promptTokens > args.maxInputTokens)
|
|
114
|
+
throw new EmbeddingsError('input-too-long', { knownUsage });
|
|
115
|
+
let vector;
|
|
116
|
+
try {
|
|
117
|
+
vector = normalizeVector(parsed.embedding.values, args.space.dimensions);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error instanceof EmbeddingsError)
|
|
121
|
+
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
|
122
|
+
knownUsage,
|
|
123
|
+
});
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
vectors: [vector],
|
|
128
|
+
usage: {
|
|
129
|
+
providerReportedInputTokens: promptTokens,
|
|
130
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
131
|
+
billedTokens: null,
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Vertex's explicit truncation flag is checked in addition to the exact preflight token count. */
|
|
136
|
+
export function parseVertexEmbeddingResponse(args) {
|
|
137
|
+
if (!Value.Check(vertexEmbeddingResponseSchema, args.response))
|
|
138
|
+
throw new EmbeddingsError('provider-response-invalid', {
|
|
139
|
+
knownUsage: { preparedInputTokens: args.preparedInputTokens },
|
|
140
|
+
});
|
|
141
|
+
if (args.response.truncated === true)
|
|
142
|
+
throw new EmbeddingsError('input-too-long', {
|
|
143
|
+
knownUsage: {
|
|
144
|
+
providerReportedInputTokens: args.response.usageMetadata.promptTokenCount,
|
|
145
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
return parseGeminiEmbeddingResponse(args);
|
|
149
|
+
}
|
|
150
|
+
/** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
|
|
151
|
+
export function parseCloudflareBatchResponse(args) {
|
|
152
|
+
const output = unwrapCloudflareModelOutput(args.response);
|
|
153
|
+
if (!Value.Check(cloudflareResponseSchema, output))
|
|
154
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
155
|
+
const parsed = output;
|
|
156
|
+
if (parsed.data.length !== args.expectedCount)
|
|
157
|
+
throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
|
|
158
|
+
let vectors;
|
|
159
|
+
try {
|
|
160
|
+
vectors = parsed.data.map((vector) => normalizeVector(vector, args.space.dimensions));
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (error instanceof EmbeddingsError)
|
|
164
|
+
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
|
165
|
+
knownUsage: {},
|
|
166
|
+
});
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
return {
|
|
170
|
+
vectors,
|
|
171
|
+
usage: {
|
|
172
|
+
providerReportedInputTokens: null,
|
|
173
|
+
preparedInputTokens: null,
|
|
174
|
+
billedTokens: null,
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spaceForRoute, type EmbeddingDiagnostic } from './providers.js';
|
|
2
|
+
import { EMBEDDINGS_PROTOCOL_VERSION, type EmbeddingCompareResult, type EmbeddingContext, type EmbeddingRequest, type EmbeddingResult, type EmbeddingRoute, type EmbeddingSettings } from './schemas.js';
|
|
2
3
|
export interface EmbeddingsRuntime {
|
|
3
4
|
/** Acquire the selected local child at MCP startup; cloud selections start no local process. */
|
|
4
5
|
start(): Promise<void>;
|
|
@@ -10,10 +11,29 @@ export interface EmbeddingsRuntime {
|
|
|
10
11
|
signal?: AbortSignal | undefined;
|
|
11
12
|
context?: EmbeddingContext | undefined;
|
|
12
13
|
}): Promise<EmbeddingCompareResult>;
|
|
13
|
-
describe(): EmbeddingDescribe;
|
|
14
14
|
close(): Promise<void>;
|
|
15
15
|
}
|
|
16
|
+
/** Internal diagnostics for Pi commands and host startup; never registered as a tool. */
|
|
17
|
+
export interface RuntimeDiagnostics {
|
|
18
|
+
readonly schemaVersion: typeof EMBEDDINGS_PROTOCOL_VERSION;
|
|
19
|
+
readonly ready: boolean;
|
|
20
|
+
readonly selected: EmbeddingRoute;
|
|
21
|
+
readonly space: ReturnType<typeof spaceForRoute> | null;
|
|
22
|
+
readonly default: EmbeddingRoute;
|
|
23
|
+
readonly fallback: readonly EmbeddingRoute[];
|
|
24
|
+
readonly compare: readonly EmbeddingRoute[];
|
|
25
|
+
readonly diagnostics: readonly EmbeddingDiagnostic[];
|
|
26
|
+
}
|
|
27
|
+
export interface EmbeddingsRuntimeWithDiagnostics extends EmbeddingsRuntime {
|
|
28
|
+
describe(): RuntimeDiagnostics;
|
|
29
|
+
}
|
|
30
|
+
/** Public factory: callers cannot obtain describe metadata from the runtime API. */
|
|
16
31
|
export declare function createEmbeddingsRuntime(args: {
|
|
17
32
|
settings: EmbeddingSettings;
|
|
18
33
|
cwd?: string | undefined;
|
|
19
34
|
}): EmbeddingsRuntime;
|
|
35
|
+
/** Package-internal factory for Pi command output and provider-free host startup checks. */
|
|
36
|
+
export declare function createEmbeddingsRuntimeWithDiagnostics(args: {
|
|
37
|
+
settings: EmbeddingSettings;
|
|
38
|
+
cwd?: string | undefined;
|
|
39
|
+
}): EmbeddingsRuntimeWithDiagnostics;
|
package/dist/runtime.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { acquireProvider, routeDiagnostics, routeKey, spaceForRoute } from './providers.js';
|
|
1
|
+
import { acquireProvider, routeDiagnostics, routeKey, spaceForRoute, } from './providers.js';
|
|
2
2
|
import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
|
|
3
3
|
import { executeCompare, executeEmbeddings } from './execute.js';
|
|
4
4
|
import { EmbeddingsError } from './errors.js';
|
|
5
5
|
import { EMBEDDINGS_PROTOCOL_VERSION, } from './schemas.js';
|
|
6
6
|
const noSignal = (signal) => signal ?? new AbortController().signal;
|
|
7
|
-
|
|
7
|
+
function createRuntime(args) {
|
|
8
8
|
const settings = validateEmbeddingSettings(args.settings);
|
|
9
9
|
const defaultRoute = configuredDefault(settings);
|
|
10
10
|
const fallbackRoutes = configuredRoutes(settings, 'fallback');
|
|
@@ -95,7 +95,7 @@ export function createEmbeddingsRuntime(args) {
|
|
|
95
95
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
96
96
|
ready: defaultDiagnostics.length === 0,
|
|
97
97
|
selected: defaultRoute,
|
|
98
|
-
space: spaceForRoute(defaultRoute),
|
|
98
|
+
space: spaceForRoute(defaultRoute, settings),
|
|
99
99
|
default: defaultRoute,
|
|
100
100
|
fallback: [...fallbackRoutes],
|
|
101
101
|
compare: [...compareRoutes],
|
|
@@ -119,3 +119,12 @@ export function createEmbeddingsRuntime(args) {
|
|
|
119
119
|
},
|
|
120
120
|
};
|
|
121
121
|
}
|
|
122
|
+
/** Public factory: callers cannot obtain describe metadata from the runtime API. */
|
|
123
|
+
export function createEmbeddingsRuntime(args) {
|
|
124
|
+
const { start, embed, compare, close } = createRuntime(args);
|
|
125
|
+
return { start, embed, compare, close };
|
|
126
|
+
}
|
|
127
|
+
/** Package-internal factory for Pi command output and provider-free host startup checks. */
|
|
128
|
+
export function createEmbeddingsRuntimeWithDiagnostics(args) {
|
|
129
|
+
return createRuntime(args);
|
|
130
|
+
}
|