@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/src/providers.ts
CHANGED
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
import { getEncoding } from 'js-tiktoken';
|
|
2
|
+
import { VertexProvider, vertexEmbeddingSpace } from './vertex-provider.js';
|
|
2
3
|
import { EmbeddingsError } from './errors.js';
|
|
3
4
|
import {
|
|
4
5
|
EMBEDDING_DOCUMENT_PREFIX,
|
|
5
6
|
EMBEDDING_FORMAT_VERSION,
|
|
6
7
|
EMBEDDING_NORMALIZATION_VERSION,
|
|
8
|
+
CLOUDFLARE_EMBEDDING_MODELS,
|
|
9
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
10
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
11
|
+
GEMINI_EMBEDDING_MODELS,
|
|
12
|
+
GEMINI_TASK_PREFIXES,
|
|
13
|
+
OPENROUTER_EMBEDDING_MODELS,
|
|
7
14
|
type EmbeddingContext,
|
|
8
|
-
type EmbeddingDiagnostic,
|
|
9
15
|
type EmbeddingRoute,
|
|
10
16
|
type EmbeddingSettings,
|
|
11
17
|
type EmbeddingSpace,
|
|
18
|
+
type GeminiEmbeddingDimension,
|
|
19
|
+
type GeminiEmbeddingTaskFormat,
|
|
12
20
|
} from './schemas.js';
|
|
13
21
|
import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
|
|
14
22
|
import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
|
|
15
23
|
import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
|
|
16
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
parseBatchResponse,
|
|
26
|
+
parseCloudflareBatchResponse,
|
|
27
|
+
parseGeminiCountTokensResponse,
|
|
28
|
+
parseGeminiEmbeddingResponse,
|
|
29
|
+
} from './response.js';
|
|
17
30
|
|
|
18
31
|
export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
|
|
19
32
|
provider: 'openai',
|
|
@@ -39,9 +52,46 @@ export const SARVAM_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
|
|
|
39
52
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
40
53
|
});
|
|
41
54
|
|
|
55
|
+
type CloudflarePooling = 'mean' | 'cls';
|
|
56
|
+
|
|
57
|
+
export const cloudflareEmbeddingSpace = (pooling: CloudflarePooling): EmbeddingSpace =>
|
|
58
|
+
Object.freeze({
|
|
59
|
+
provider: 'cloudflare',
|
|
60
|
+
model: CLOUDFLARE_EMBEDDING_MODELS[0],
|
|
61
|
+
revision: null,
|
|
62
|
+
quantization: null,
|
|
63
|
+
runtime: 'cloudflare-workers-ai',
|
|
64
|
+
dimensions: 768,
|
|
65
|
+
pooling,
|
|
66
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
67
|
+
prefix: EMBEDDING_DOCUMENT_PREFIX,
|
|
68
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
export const geminiEmbeddingSpace = (config: {
|
|
72
|
+
dimensions: GeminiEmbeddingDimension;
|
|
73
|
+
taskFormat: GeminiEmbeddingTaskFormat;
|
|
74
|
+
}): EmbeddingSpace =>
|
|
75
|
+
Object.freeze({
|
|
76
|
+
provider: 'gemini',
|
|
77
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
78
|
+
revision: null,
|
|
79
|
+
quantization: null,
|
|
80
|
+
runtime: 'gemini-api-v1beta',
|
|
81
|
+
dimensions: config.dimensions,
|
|
82
|
+
taskFormat: config.taskFormat,
|
|
83
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
84
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
85
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
86
|
+
});
|
|
87
|
+
|
|
42
88
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
43
89
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
44
90
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
91
|
+
const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
|
|
92
|
+
const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
|
|
93
|
+
const GEMINI_ORIGIN = 'https://generativelanguage.googleapis.com';
|
|
94
|
+
const GEMINI_MAX_INPUT_TOKENS = 8192;
|
|
45
95
|
|
|
46
96
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
47
97
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
@@ -54,6 +104,11 @@ const trim = (value: string | undefined): string | undefined => {
|
|
|
54
104
|
|
|
55
105
|
export const routeKey = (route: EmbeddingRoute): string => `${route.provider}\u0000${route.model}`;
|
|
56
106
|
|
|
107
|
+
export type EmbeddingDiagnostic = Readonly<{
|
|
108
|
+
readonly code: string;
|
|
109
|
+
readonly severity: 'error' | 'warning' | 'info';
|
|
110
|
+
}>;
|
|
111
|
+
|
|
57
112
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
58
113
|
export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[] {
|
|
59
114
|
const diagnostics: EmbeddingDiagnostic[] = [];
|
|
@@ -83,6 +138,28 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
|
|
|
83
138
|
add('gateway-key-unconfigured');
|
|
84
139
|
break;
|
|
85
140
|
}
|
|
141
|
+
case 'openrouter':
|
|
142
|
+
if (trim(settings.providers?.openrouter?.apiKey) === undefined && trim(process.env.OPENROUTER_API_KEY) === undefined)
|
|
143
|
+
add('openrouter-key-unconfigured');
|
|
144
|
+
break;
|
|
145
|
+
case 'cloudflare': {
|
|
146
|
+
const cloudflare = settings.providers?.cloudflare;
|
|
147
|
+
if (trim(cloudflare?.accountId) === undefined && trim(process.env.CLOUDFLARE_ACCOUNT_ID) === undefined)
|
|
148
|
+
add('cloudflare-account-unconfigured');
|
|
149
|
+
if (trim(cloudflare?.apiKey) === undefined && trim(process.env.CLOUDFLARE_API_TOKEN) === undefined)
|
|
150
|
+
add('cloudflare-key-unconfigured');
|
|
151
|
+
if (trim(cloudflare?.gatewayId) === undefined && trim(process.env.CLOUDFLARE_AI_GATEWAY_ID) === undefined)
|
|
152
|
+
add('cloudflare-gateway-unconfigured');
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case 'gemini':
|
|
156
|
+
if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
|
|
157
|
+
add('gemini-key-unconfigured');
|
|
158
|
+
break;
|
|
159
|
+
case 'vertex':
|
|
160
|
+
if (settings.providers?.vertex === undefined) add('vertex-configuration-unconfigured');
|
|
161
|
+
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
162
|
+
break;
|
|
86
163
|
}
|
|
87
164
|
return diagnostics;
|
|
88
165
|
}
|
|
@@ -93,6 +170,12 @@ const credential = (configured: string | undefined, env: string | undefined): st
|
|
|
93
170
|
return value;
|
|
94
171
|
};
|
|
95
172
|
|
|
173
|
+
const headerCredential = (configured: string | undefined, env: string | undefined): string => {
|
|
174
|
+
const value = credential(configured, env);
|
|
175
|
+
if (!headerValueIsSafe(value)) throw new EmbeddingsError('configuration-invalid');
|
|
176
|
+
return value;
|
|
177
|
+
};
|
|
178
|
+
|
|
96
179
|
/** The documented text-string path avoids the token-array schema contradiction without truncating. */
|
|
97
180
|
const openAIPrepare = (
|
|
98
181
|
encoding: ReturnType<typeof getEncoding>,
|
|
@@ -257,6 +340,179 @@ class GatewayProvider implements EmbeddingsProvider {
|
|
|
257
340
|
}
|
|
258
341
|
}
|
|
259
342
|
|
|
343
|
+
class OpenRouterProvider implements EmbeddingsProvider {
|
|
344
|
+
readonly route = 'openrouter' as const;
|
|
345
|
+
readonly model = OPENROUTER_EMBEDDING_MODELS[0];
|
|
346
|
+
readonly space: EmbeddingSpace = OPENAI_EMBEDDING_SPACE;
|
|
347
|
+
readonly maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
|
|
348
|
+
readonly maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
|
|
349
|
+
readonly #encoding = getEncoding('cl100k_base');
|
|
350
|
+
readonly #key: string;
|
|
351
|
+
|
|
352
|
+
constructor(key: string) {
|
|
353
|
+
this.#key = key;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
357
|
+
return openAIPrepare(this.#encoding, text, signal);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
361
|
+
const response = await requestJson({
|
|
362
|
+
url: new URL(OPENROUTER_EMBEDDINGS_URL),
|
|
363
|
+
signal,
|
|
364
|
+
headers: { authorization: `Bearer ${this.#key}` },
|
|
365
|
+
body: {
|
|
366
|
+
model: this.model,
|
|
367
|
+
dimensions: this.space.dimensions,
|
|
368
|
+
input: providerTexts(inputs),
|
|
369
|
+
encoding_format: 'float',
|
|
370
|
+
},
|
|
371
|
+
});
|
|
372
|
+
const count = preparedTokens(inputs);
|
|
373
|
+
return parseBatchResponse({
|
|
374
|
+
response,
|
|
375
|
+
space: this.space,
|
|
376
|
+
expectedModels: [this.model],
|
|
377
|
+
expectedPreparedTokens: count,
|
|
378
|
+
preparedInputTokens: count,
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async close(): Promise<void> {
|
|
383
|
+
// js-tiktoken is pure JavaScript and owns no process or handle.
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
class CloudflareProvider implements EmbeddingsProvider {
|
|
388
|
+
readonly route = 'cloudflare' as const;
|
|
389
|
+
readonly model = CLOUDFLARE_EMBEDDING_MODELS[0];
|
|
390
|
+
readonly space: EmbeddingSpace;
|
|
391
|
+
// Workers AI documents a 512-token input ceiling for this model but no aggregate request cap.
|
|
392
|
+
// The model-owned tokenizer is not available here, so no approximate local cap is invented.
|
|
393
|
+
readonly maxRequestInputs = Number.POSITIVE_INFINITY;
|
|
394
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
395
|
+
readonly #url: URL;
|
|
396
|
+
readonly #key: string;
|
|
397
|
+
readonly #gatewayId: string;
|
|
398
|
+
readonly #pooling: CloudflarePooling;
|
|
399
|
+
|
|
400
|
+
constructor(config: {
|
|
401
|
+
accountId: string;
|
|
402
|
+
apiKey: string;
|
|
403
|
+
gatewayId: string;
|
|
404
|
+
model: typeof CLOUDFLARE_EMBEDDING_MODELS[number];
|
|
405
|
+
pooling: CloudflarePooling;
|
|
406
|
+
}) {
|
|
407
|
+
this.#url = new URL(
|
|
408
|
+
`${CLOUDFLARE_ORIGIN}/${encodeURIComponent(config.accountId)}/ai/run/${config.model}`
|
|
409
|
+
);
|
|
410
|
+
this.#key = config.apiKey;
|
|
411
|
+
this.#gatewayId = config.gatewayId;
|
|
412
|
+
this.#pooling = config.pooling;
|
|
413
|
+
this.space = cloudflareEmbeddingSpace(config.pooling);
|
|
414
|
+
// The model is pinned from settings; this guard keeps the fixed URL invariant explicit.
|
|
415
|
+
if (config.model !== CLOUDFLARE_EMBEDDING_MODELS[0])
|
|
416
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
420
|
+
signal.throwIfAborted();
|
|
421
|
+
return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
425
|
+
const response = await requestJson({
|
|
426
|
+
url: this.#url,
|
|
427
|
+
signal,
|
|
428
|
+
headers: {
|
|
429
|
+
authorization: `Bearer ${this.#key}`,
|
|
430
|
+
'cf-aig-gateway-id': this.#gatewayId,
|
|
431
|
+
},
|
|
432
|
+
body: { text: providerTexts(inputs), pooling: this.#pooling },
|
|
433
|
+
});
|
|
434
|
+
return parseCloudflareBatchResponse({
|
|
435
|
+
response,
|
|
436
|
+
space: this.space,
|
|
437
|
+
expectedCount: inputs.length,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async close(): Promise<void> {
|
|
442
|
+
// Native fetch owns no long-lived resource.
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
class GeminiProvider implements EmbeddingsProvider {
|
|
447
|
+
readonly route = 'gemini' as const;
|
|
448
|
+
readonly model = GEMINI_EMBEDDING_MODELS[0];
|
|
449
|
+
readonly space: EmbeddingSpace;
|
|
450
|
+
// One exact prepared prompt is counted and embedded per request; no vector is accepted unless the
|
|
451
|
+
// embed response token count equals that preflight count.
|
|
452
|
+
readonly maxRequestInputs = 1;
|
|
453
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
454
|
+
readonly #url = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:embedContent`, GEMINI_ORIGIN);
|
|
455
|
+
readonly #countUrl = new URL(
|
|
456
|
+
`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:countTokens`,
|
|
457
|
+
GEMINI_ORIGIN
|
|
458
|
+
);
|
|
459
|
+
readonly #key: string;
|
|
460
|
+
readonly #taskFormat: GeminiEmbeddingTaskFormat;
|
|
461
|
+
|
|
462
|
+
constructor(key: string, config: {
|
|
463
|
+
dimensions: GeminiEmbeddingDimension;
|
|
464
|
+
taskFormat: GeminiEmbeddingTaskFormat;
|
|
465
|
+
}) {
|
|
466
|
+
this.#key = key;
|
|
467
|
+
this.#taskFormat = config.taskFormat;
|
|
468
|
+
this.space = geminiEmbeddingSpace(config);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
472
|
+
signal.throwIfAborted();
|
|
473
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#taskFormat] + text;
|
|
474
|
+
const response = await requestJson({
|
|
475
|
+
url: this.#countUrl,
|
|
476
|
+
signal,
|
|
477
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
478
|
+
body: { contents: [{ parts: [{ text: prepared }] }] },
|
|
479
|
+
});
|
|
480
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
481
|
+
if (tokenCount > GEMINI_MAX_INPUT_TOKENS)
|
|
482
|
+
throw new EmbeddingsError('input-too-long', {
|
|
483
|
+
knownUsage: { preparedInputTokens: tokenCount },
|
|
484
|
+
});
|
|
485
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
489
|
+
const text = providerTexts(inputs)[0];
|
|
490
|
+
if (inputs.length !== 1 || text === undefined)
|
|
491
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
492
|
+
const preparedInputTokens = preparedTokens(inputs);
|
|
493
|
+
const response = await requestJson({
|
|
494
|
+
url: this.#url,
|
|
495
|
+
signal,
|
|
496
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
497
|
+
body: {
|
|
498
|
+
model: `models/${this.model}`,
|
|
499
|
+
content: { parts: [{ text }] },
|
|
500
|
+
output_dimensionality: this.space.dimensions,
|
|
501
|
+
},
|
|
502
|
+
});
|
|
503
|
+
return parseGeminiEmbeddingResponse({
|
|
504
|
+
response,
|
|
505
|
+
space: this.space,
|
|
506
|
+
maxInputTokens: GEMINI_MAX_INPUT_TOKENS,
|
|
507
|
+
preparedInputTokens,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async close(): Promise<void> {
|
|
512
|
+
// Native fetch owns no long-lived resource.
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
260
516
|
export type AcquiredProvider = Readonly<{
|
|
261
517
|
readonly provider: EmbeddingsProvider;
|
|
262
518
|
readonly release: () => Promise<void>;
|
|
@@ -319,17 +575,80 @@ export async function acquireProvider({
|
|
|
319
575
|
release: noRelease,
|
|
320
576
|
};
|
|
321
577
|
}
|
|
578
|
+
case 'openrouter':
|
|
579
|
+
return {
|
|
580
|
+
provider: new OpenRouterProvider(
|
|
581
|
+
headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)
|
|
582
|
+
),
|
|
583
|
+
release: noRelease,
|
|
584
|
+
};
|
|
585
|
+
case 'cloudflare': {
|
|
586
|
+
const configured = settings.providers?.cloudflare;
|
|
587
|
+
const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
|
|
588
|
+
const gatewayId = trim(configured?.gatewayId) ?? trim(process.env.CLOUDFLARE_AI_GATEWAY_ID);
|
|
589
|
+
if (accountId === undefined || gatewayId === undefined)
|
|
590
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
591
|
+
if (!headerValueIsSafe(accountId) || !headerValueIsSafe(gatewayId))
|
|
592
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
593
|
+
const model = trim(configured?.model) ?? CLOUDFLARE_EMBEDDING_MODELS[0];
|
|
594
|
+
if (model !== CLOUDFLARE_EMBEDDING_MODELS[0]) throw new EmbeddingsError('configuration-invalid');
|
|
595
|
+
const pooling: CloudflarePooling = configured?.pooling ?? 'mean';
|
|
596
|
+
return {
|
|
597
|
+
provider: new CloudflareProvider({
|
|
598
|
+
accountId,
|
|
599
|
+
apiKey: headerCredential(configured?.apiKey, process.env.CLOUDFLARE_API_TOKEN),
|
|
600
|
+
gatewayId,
|
|
601
|
+
model,
|
|
602
|
+
pooling,
|
|
603
|
+
}),
|
|
604
|
+
release: noRelease,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
case 'vertex': {
|
|
608
|
+
const configured = settings.providers?.vertex;
|
|
609
|
+
if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
|
|
610
|
+
return { provider: new VertexProvider(configured), release: noRelease };
|
|
611
|
+
}
|
|
612
|
+
case 'gemini': {
|
|
613
|
+
const configured = settings.providers?.gemini;
|
|
614
|
+
return {
|
|
615
|
+
provider: new GeminiProvider(
|
|
616
|
+
headerCredential(configured?.apiKey, process.env.GEMINI_API_KEY),
|
|
617
|
+
{
|
|
618
|
+
dimensions: configured?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
619
|
+
taskFormat: configured?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
620
|
+
}
|
|
621
|
+
),
|
|
622
|
+
release: noRelease,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
322
625
|
}
|
|
323
626
|
}
|
|
324
627
|
|
|
325
|
-
export const spaceForRoute = (
|
|
628
|
+
export const spaceForRoute = (
|
|
629
|
+
route: EmbeddingRoute,
|
|
630
|
+
settings?: EmbeddingSettings | undefined
|
|
631
|
+
): EmbeddingSpace => {
|
|
326
632
|
switch (route.provider) {
|
|
327
633
|
case 'local':
|
|
328
634
|
return LOCAL_EMBEDDING_SPACE;
|
|
329
635
|
case 'openai':
|
|
330
636
|
case 'gateway':
|
|
637
|
+
case 'openrouter':
|
|
331
638
|
return OPENAI_EMBEDDING_SPACE;
|
|
332
639
|
case 'sarvam':
|
|
333
640
|
return SARVAM_EMBEDDING_SPACE;
|
|
641
|
+
case 'cloudflare':
|
|
642
|
+
return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
|
|
643
|
+
case 'vertex': {
|
|
644
|
+
const configured = settings?.providers?.vertex;
|
|
645
|
+
if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
|
|
646
|
+
return vertexEmbeddingSpace(configured);
|
|
647
|
+
}
|
|
648
|
+
case 'gemini':
|
|
649
|
+
return geminiEmbeddingSpace({
|
|
650
|
+
dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
651
|
+
taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
652
|
+
});
|
|
334
653
|
}
|
|
335
654
|
};
|
package/src/response.ts
CHANGED
|
@@ -17,6 +17,46 @@ const responseSchema = Type.Object({
|
|
|
17
17
|
}),
|
|
18
18
|
});
|
|
19
19
|
|
|
20
|
+
const cloudflareResponseSchema = Type.Object({
|
|
21
|
+
shape: Type.Optional(Type.Array(Type.Integer({ minimum: 0 }))),
|
|
22
|
+
data: Type.Array(Type.Array(Type.Number())),
|
|
23
|
+
pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const geminiEmbeddingResponseSchema = Type.Object({
|
|
27
|
+
embedding: Type.Object({ values: Type.Array(Type.Number()) }),
|
|
28
|
+
usageMetadata: Type.Object({ promptTokenCount: Type.Integer({ minimum: 0 }) }),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const vertexEmbeddingResponseSchema = Type.Object({
|
|
32
|
+
...geminiEmbeddingResponseSchema.properties,
|
|
33
|
+
truncated: Type.Optional(Type.Boolean()),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const geminiCountTokensResponseSchema = Type.Object({
|
|
37
|
+
totalTokens: Type.Integer({ minimum: 0 }),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** Exact prepared-prompt count from the model's own tokenizer, used before inference. */
|
|
41
|
+
export function parseGeminiCountTokensResponse(response: unknown): number {
|
|
42
|
+
if (!Value.Check(geminiCountTokensResponseSchema, response))
|
|
43
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
44
|
+
return response.totalTokens;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
|
|
48
|
+
function unwrapCloudflareModelOutput(response: unknown): unknown {
|
|
49
|
+
if (typeof response !== 'object' || response === null || Array.isArray(response))
|
|
50
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
51
|
+
const envelope = response as Record<string, unknown>;
|
|
52
|
+
if (
|
|
53
|
+
envelope.success === false ||
|
|
54
|
+
(Array.isArray(envelope.errors) && envelope.errors.length > 0)
|
|
55
|
+
)
|
|
56
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
57
|
+
return Object.hasOwn(envelope, 'result') ? envelope.result : envelope;
|
|
58
|
+
}
|
|
59
|
+
|
|
20
60
|
/** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
|
|
21
61
|
export function normalizeVector(vector: readonly number[], dimensions: number): number[] {
|
|
22
62
|
if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
|
|
@@ -72,3 +112,98 @@ export function parseBatchResponse(args: {
|
|
|
72
112
|
},
|
|
73
113
|
};
|
|
74
114
|
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
|
|
118
|
+
* only when that response count matches the exact prepared prompt counted before inference; a mismatch
|
|
119
|
+
* or over-limit count fails closed instead of relying on undocumented truncation semantics.
|
|
120
|
+
*/
|
|
121
|
+
export function parseGeminiEmbeddingResponse(args: {
|
|
122
|
+
response: unknown;
|
|
123
|
+
space: EmbeddingSpace;
|
|
124
|
+
maxInputTokens: number;
|
|
125
|
+
preparedInputTokens: number;
|
|
126
|
+
}): ProviderBatchResult {
|
|
127
|
+
if (!Value.Check(geminiEmbeddingResponseSchema, args.response))
|
|
128
|
+
throw new EmbeddingsError('provider-response-invalid', {
|
|
129
|
+
knownUsage: { preparedInputTokens: args.preparedInputTokens },
|
|
130
|
+
});
|
|
131
|
+
const parsed = args.response;
|
|
132
|
+
const promptTokens = parsed.usageMetadata.promptTokenCount;
|
|
133
|
+
const knownUsage = {
|
|
134
|
+
providerReportedInputTokens: promptTokens,
|
|
135
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
136
|
+
};
|
|
137
|
+
if (promptTokens !== args.preparedInputTokens)
|
|
138
|
+
throw new EmbeddingsError('provider-response-mismatch', { knownUsage });
|
|
139
|
+
if (promptTokens > args.maxInputTokens)
|
|
140
|
+
throw new EmbeddingsError('input-too-long', { knownUsage });
|
|
141
|
+
let vector: number[];
|
|
142
|
+
try {
|
|
143
|
+
vector = normalizeVector(parsed.embedding.values, args.space.dimensions);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (error instanceof EmbeddingsError)
|
|
146
|
+
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
|
147
|
+
knownUsage,
|
|
148
|
+
});
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
vectors: [vector],
|
|
153
|
+
usage: {
|
|
154
|
+
providerReportedInputTokens: promptTokens,
|
|
155
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
156
|
+
billedTokens: null,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Vertex's explicit truncation flag is checked in addition to the exact preflight token count. */
|
|
162
|
+
export function parseVertexEmbeddingResponse(
|
|
163
|
+
args: Parameters<typeof parseGeminiEmbeddingResponse>[0]
|
|
164
|
+
): ProviderBatchResult {
|
|
165
|
+
if (!Value.Check(vertexEmbeddingResponseSchema, args.response))
|
|
166
|
+
throw new EmbeddingsError('provider-response-invalid', {
|
|
167
|
+
knownUsage: { preparedInputTokens: args.preparedInputTokens },
|
|
168
|
+
});
|
|
169
|
+
if (args.response.truncated === true)
|
|
170
|
+
throw new EmbeddingsError('input-too-long', {
|
|
171
|
+
knownUsage: {
|
|
172
|
+
providerReportedInputTokens: args.response.usageMetadata.promptTokenCount,
|
|
173
|
+
preparedInputTokens: args.preparedInputTokens,
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
return parseGeminiEmbeddingResponse(args);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
|
|
180
|
+
export function parseCloudflareBatchResponse(args: {
|
|
181
|
+
response: unknown;
|
|
182
|
+
space: EmbeddingSpace;
|
|
183
|
+
expectedCount: number;
|
|
184
|
+
}): ProviderBatchResult {
|
|
185
|
+
const output = unwrapCloudflareModelOutput(args.response);
|
|
186
|
+
if (!Value.Check(cloudflareResponseSchema, output))
|
|
187
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
188
|
+
const parsed = output;
|
|
189
|
+
if (parsed.data.length !== args.expectedCount)
|
|
190
|
+
throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
|
|
191
|
+
let vectors: number[][];
|
|
192
|
+
try {
|
|
193
|
+
vectors = parsed.data.map((vector) => normalizeVector(vector, args.space.dimensions));
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error instanceof EmbeddingsError)
|
|
196
|
+
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
|
197
|
+
knownUsage: {},
|
|
198
|
+
});
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
vectors,
|
|
203
|
+
usage: {
|
|
204
|
+
providerReportedInputTokens: null,
|
|
205
|
+
preparedInputTokens: null,
|
|
206
|
+
billedTokens: null,
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
package/src/runtime.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
acquireProvider,
|
|
3
|
+
routeDiagnostics,
|
|
4
|
+
routeKey,
|
|
5
|
+
spaceForRoute,
|
|
6
|
+
type AcquiredProvider,
|
|
7
|
+
type EmbeddingDiagnostic,
|
|
8
|
+
} from './providers.js';
|
|
2
9
|
import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
|
|
3
10
|
import { executeCompare, executeEmbeddings } from './execute.js';
|
|
4
11
|
import { EmbeddingsError } from './errors.js';
|
|
@@ -6,7 +13,6 @@ import {
|
|
|
6
13
|
EMBEDDINGS_PROTOCOL_VERSION,
|
|
7
14
|
type EmbeddingCompareResult,
|
|
8
15
|
type EmbeddingContext,
|
|
9
|
-
type EmbeddingDescribe,
|
|
10
16
|
type EmbeddingRequest,
|
|
11
17
|
type EmbeddingResult,
|
|
12
18
|
type EmbeddingRoute,
|
|
@@ -24,16 +30,31 @@ export interface EmbeddingsRuntime {
|
|
|
24
30
|
request: EmbeddingRequest,
|
|
25
31
|
options?: { signal?: AbortSignal | undefined; context?: EmbeddingContext | undefined }
|
|
26
32
|
): Promise<EmbeddingCompareResult>;
|
|
27
|
-
describe(): EmbeddingDescribe;
|
|
28
33
|
close(): Promise<void>;
|
|
29
34
|
}
|
|
30
35
|
|
|
36
|
+
/** Internal diagnostics for Pi commands and host startup; never registered as a tool. */
|
|
37
|
+
export interface RuntimeDiagnostics {
|
|
38
|
+
readonly schemaVersion: typeof EMBEDDINGS_PROTOCOL_VERSION;
|
|
39
|
+
readonly ready: boolean;
|
|
40
|
+
readonly selected: EmbeddingRoute;
|
|
41
|
+
readonly space: ReturnType<typeof spaceForRoute> | null;
|
|
42
|
+
readonly default: EmbeddingRoute;
|
|
43
|
+
readonly fallback: readonly EmbeddingRoute[];
|
|
44
|
+
readonly compare: readonly EmbeddingRoute[];
|
|
45
|
+
readonly diagnostics: readonly EmbeddingDiagnostic[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface EmbeddingsRuntimeWithDiagnostics extends EmbeddingsRuntime {
|
|
49
|
+
describe(): RuntimeDiagnostics;
|
|
50
|
+
}
|
|
51
|
+
|
|
31
52
|
const noSignal = (signal: AbortSignal | undefined): AbortSignal => signal ?? new AbortController().signal;
|
|
32
53
|
|
|
33
|
-
|
|
54
|
+
function createRuntime(args: {
|
|
34
55
|
settings: EmbeddingSettings;
|
|
35
56
|
cwd?: string | undefined;
|
|
36
|
-
}):
|
|
57
|
+
}): EmbeddingsRuntimeWithDiagnostics {
|
|
37
58
|
const settings = validateEmbeddingSettings(args.settings);
|
|
38
59
|
const defaultRoute = configuredDefault(settings);
|
|
39
60
|
const fallbackRoutes = configuredRoutes(settings, 'fallback');
|
|
@@ -121,7 +142,7 @@ export function createEmbeddingsRuntime(args: {
|
|
|
121
142
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
122
143
|
ready: defaultDiagnostics.length === 0,
|
|
123
144
|
selected: defaultRoute,
|
|
124
|
-
space: spaceForRoute(defaultRoute),
|
|
145
|
+
space: spaceForRoute(defaultRoute, settings),
|
|
125
146
|
default: defaultRoute,
|
|
126
147
|
fallback: [...fallbackRoutes],
|
|
127
148
|
compare: [...compareRoutes],
|
|
@@ -144,3 +165,20 @@ export function createEmbeddingsRuntime(args: {
|
|
|
144
165
|
},
|
|
145
166
|
};
|
|
146
167
|
}
|
|
168
|
+
|
|
169
|
+
/** Public factory: callers cannot obtain describe metadata from the runtime API. */
|
|
170
|
+
export function createEmbeddingsRuntime(args: {
|
|
171
|
+
settings: EmbeddingSettings;
|
|
172
|
+
cwd?: string | undefined;
|
|
173
|
+
}): EmbeddingsRuntime {
|
|
174
|
+
const { start, embed, compare, close } = createRuntime(args);
|
|
175
|
+
return { start, embed, compare, close };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Package-internal factory for Pi command output and provider-free host startup checks. */
|
|
179
|
+
export function createEmbeddingsRuntimeWithDiagnostics(args: {
|
|
180
|
+
settings: EmbeddingSettings;
|
|
181
|
+
cwd?: string | undefined;
|
|
182
|
+
}): EmbeddingsRuntimeWithDiagnostics {
|
|
183
|
+
return createRuntime(args);
|
|
184
|
+
}
|