@abhishek944/pi-embeddings 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +97 -2
  3. package/dist/errors.d.ts +21 -0
  4. package/dist/errors.js +41 -0
  5. package/dist/execute.d.ts +25 -0
  6. package/dist/execute.js +264 -0
  7. package/dist/extension.d.ts +2 -0
  8. package/dist/extension.js +164 -0
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +4 -0
  11. package/dist/local-runtime.d.ts +14 -0
  12. package/dist/local-runtime.js +246 -0
  13. package/dist/mcp-cli.d.ts +2 -0
  14. package/dist/mcp-cli.js +46 -0
  15. package/dist/mcp-server.d.ts +23 -0
  16. package/dist/mcp-server.js +141 -0
  17. package/dist/provider-http.d.ts +11 -0
  18. package/dist/provider-http.js +60 -0
  19. package/dist/provider-types.d.ts +30 -0
  20. package/dist/provider-types.js +1 -0
  21. package/dist/providers.d.ts +25 -0
  22. package/dist/providers.js +415 -0
  23. package/dist/response.d.ts +17 -0
  24. package/dist/response.js +105 -0
  25. package/dist/runtime.d.ts +39 -0
  26. package/dist/runtime.js +130 -0
  27. package/dist/schemas.d.ts +758 -0
  28. package/dist/schemas.js +244 -0
  29. package/dist/settings-write.d.ts +9 -0
  30. package/dist/settings-write.js +77 -0
  31. package/dist/settings.d.ts +8 -0
  32. package/dist/settings.js +99 -0
  33. package/dist/tool-contracts.d.ts +343 -0
  34. package/dist/tool-contracts.js +10 -0
  35. package/package.json +83 -4
  36. package/src/errors.ts +52 -0
  37. package/src/execute.ts +300 -0
  38. package/src/extension.ts +210 -0
  39. package/src/index.ts +36 -0
  40. package/src/local-runtime.ts +273 -0
  41. package/src/mcp-cli.ts +52 -0
  42. package/src/mcp-server.ts +187 -0
  43. package/src/provider-http.ts +67 -0
  44. package/src/provider-types.ts +33 -0
  45. package/src/providers.ts +517 -0
  46. package/src/response.ts +125 -0
  47. package/src/runtime.ts +184 -0
  48. package/src/schemas.ts +368 -0
  49. package/src/settings-write.ts +96 -0
  50. package/src/settings.ts +119 -0
  51. package/src/tool-contracts.ts +22 -0
@@ -0,0 +1,60 @@
1
+ import { EmbeddingsError, statusCode } from './errors.js';
2
+ /** Native fetch with fixed URLs, no retries and no response bodies in diagnostics. */
3
+ export async function requestJson(args) {
4
+ let response;
5
+ try {
6
+ response = await fetch(args.url, {
7
+ method: 'POST',
8
+ headers: {
9
+ 'content-type': 'application/json',
10
+ accept: 'application/json',
11
+ ...args.headers,
12
+ },
13
+ body: JSON.stringify(args.body),
14
+ signal: args.signal,
15
+ redirect: 'error',
16
+ });
17
+ }
18
+ catch (error) {
19
+ if (args.signal.aborted)
20
+ throw new EmbeddingsError('cancelled');
21
+ void error;
22
+ throw new EmbeddingsError('transport-failed');
23
+ }
24
+ if (!response.ok) {
25
+ const code = statusCode(response.status);
26
+ throw new EmbeddingsError(code, { httpStatus: response.status });
27
+ }
28
+ try {
29
+ return (await response.json());
30
+ }
31
+ catch {
32
+ throw new EmbeddingsError('provider-response-invalid');
33
+ }
34
+ }
35
+ /** Fixed origins only; project settings cannot introduce an arbitrary provider endpoint. */
36
+ export const fixedOrigin = (raw) => {
37
+ let url;
38
+ try {
39
+ url = new URL(raw);
40
+ }
41
+ catch {
42
+ throw new EmbeddingsError('configuration-invalid');
43
+ }
44
+ const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
45
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
46
+ url.username !== '' ||
47
+ url.password !== '' ||
48
+ url.search !== '' ||
49
+ url.hash !== '')
50
+ throw new EmbeddingsError('configuration-invalid');
51
+ url.pathname = '';
52
+ url.search = '';
53
+ url.hash = '';
54
+ return url;
55
+ };
56
+ /** One-line header values with no control characters are the only labels this package forwards. */
57
+ export const headerValueIsSafe = (value) => value.length > 0 && [...value].every((character) => {
58
+ const code = character.codePointAt(0) ?? 0;
59
+ return code >= 0x20 && code !== 0x7f;
60
+ });
@@ -0,0 +1,30 @@
1
+ import type { EmbeddingContext, EmbeddingRouteId, EmbeddingSpace } from './schemas.js';
2
+ /** The prepared form is provider-owned and never exposed as a model-facing caller input. */
3
+ export type PreparedInput = Readonly<{
4
+ readonly kind: 'text';
5
+ readonly text: string;
6
+ readonly tokenCount: number | null;
7
+ }> | Readonly<{
8
+ readonly kind: 'tokens';
9
+ readonly tokens: readonly number[];
10
+ }>;
11
+ export type ProviderUsage = Readonly<{
12
+ readonly providerReportedInputTokens: number | null;
13
+ readonly preparedInputTokens: number | null;
14
+ readonly billedTokens: number | null;
15
+ }>;
16
+ export type ProviderBatchResult = Readonly<{
17
+ readonly vectors: readonly (readonly number[])[];
18
+ readonly usage: ProviderUsage;
19
+ }>;
20
+ export interface EmbeddingsProvider {
21
+ readonly route: EmbeddingRouteId;
22
+ readonly model: string;
23
+ readonly space: EmbeddingSpace;
24
+ /** Mandatory provider request boundaries. Infinity means no declared request-level ceiling. */
25
+ readonly maxRequestInputs: number;
26
+ readonly maxRequestTokens: number;
27
+ prepare(text: string, signal: AbortSignal): Promise<PreparedInput>;
28
+ embed(inputs: readonly PreparedInput[], signal: AbortSignal, context: EmbeddingContext | undefined): Promise<ProviderBatchResult>;
29
+ close(): Promise<void>;
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
2
+ import type { EmbeddingsProvider } from './provider-types.js';
3
+ export declare const OPENAI_EMBEDDING_SPACE: EmbeddingSpace;
4
+ export declare const SARVAM_EMBEDDING_SPACE: EmbeddingSpace;
5
+ type CloudflarePooling = 'mean' | 'cls';
6
+ export declare const cloudflareEmbeddingSpace: (pooling: CloudflarePooling) => EmbeddingSpace;
7
+ export declare const routeKey: (route: EmbeddingRoute) => string;
8
+ export type EmbeddingDiagnostic = Readonly<{
9
+ readonly code: string;
10
+ readonly severity: 'error' | 'warning' | 'info';
11
+ }>;
12
+ /** Diagnostics are provider-free and never contain keys, origins or model paths. */
13
+ export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[];
14
+ export type AcquiredProvider = Readonly<{
15
+ readonly provider: EmbeddingsProvider;
16
+ readonly release: () => Promise<void>;
17
+ }>;
18
+ /** Resolve a configured route only when that route is actually about to be used. */
19
+ export declare function acquireProvider({ settings, route, signal, }: {
20
+ settings: EmbeddingSettings;
21
+ route: EmbeddingRoute;
22
+ signal: AbortSignal;
23
+ }): Promise<AcquiredProvider>;
24
+ export declare const spaceForRoute: (route: EmbeddingRoute, settings?: EmbeddingSettings | undefined) => EmbeddingSpace;
25
+ export {};
@@ -0,0 +1,415 @@
1
+ import { getEncoding } from 'js-tiktoken';
2
+ import { EmbeddingsError } from './errors.js';
3
+ import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, OPENROUTER_EMBEDDING_MODELS, } from './schemas.js';
4
+ import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
5
+ import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
6
+ import { parseBatchResponse, parseCloudflareBatchResponse } from './response.js';
7
+ export const OPENAI_EMBEDDING_SPACE = Object.freeze({
8
+ provider: 'openai',
9
+ model: 'text-embedding-3-small',
10
+ revision: null,
11
+ quantization: null,
12
+ runtime: null,
13
+ dimensions: 1536,
14
+ format: EMBEDDING_FORMAT_VERSION,
15
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
16
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
17
+ });
18
+ export const SARVAM_EMBEDDING_SPACE = Object.freeze({
19
+ provider: 'sarvam',
20
+ model: 'embeddinggemma-2',
21
+ revision: null,
22
+ quantization: null,
23
+ runtime: 'sarvam-v2',
24
+ dimensions: 768,
25
+ format: EMBEDDING_FORMAT_VERSION,
26
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
27
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
28
+ });
29
+ export const cloudflareEmbeddingSpace = (pooling) => Object.freeze({
30
+ provider: 'cloudflare',
31
+ model: CLOUDFLARE_EMBEDDING_MODELS[0],
32
+ revision: null,
33
+ quantization: null,
34
+ runtime: 'cloudflare-workers-ai',
35
+ dimensions: 768,
36
+ pooling,
37
+ format: EMBEDDING_FORMAT_VERSION,
38
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
39
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
40
+ });
41
+ const OPENAI_MODEL = 'text-embedding-3-small';
42
+ const SARVAM_MODEL = 'embeddinggemma-2';
43
+ const SARVAM_ORIGIN = 'https://api.sarvam.ai';
44
+ const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
45
+ const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
46
+ const OPENAI_MAX_INPUT_TOKENS = 8192;
47
+ const OPENAI_MAX_REQUEST_INPUTS = 2048;
48
+ const OPENAI_MAX_REQUEST_TOKENS = 300000;
49
+ const trim = (value) => {
50
+ const trimmed = value?.trim();
51
+ return trimmed === undefined || trimmed === '' ? undefined : trimmed;
52
+ };
53
+ export const routeKey = (route) => `${route.provider}\u0000${route.model}`;
54
+ /** Diagnostics are provider-free and never contain keys, origins or model paths. */
55
+ export function routeDiagnostics(settings, route) {
56
+ const diagnostics = [];
57
+ const add = (code, severity = 'error') => {
58
+ diagnostics.push({ code, severity });
59
+ };
60
+ switch (route.provider) {
61
+ case 'local': {
62
+ const local = settings.providers?.local;
63
+ if (trim(local?.executable) === undefined || trim(local?.modelPath) === undefined)
64
+ add('local-assets-unconfigured');
65
+ break;
66
+ }
67
+ case 'openai':
68
+ if (trim(settings.providers?.openai?.apiKey) === undefined && trim(process.env.OPENAI_API_KEY) === undefined)
69
+ add('openai-key-unconfigured');
70
+ break;
71
+ case 'sarvam':
72
+ if (trim(settings.providers?.sarvam?.apiKey) === undefined && trim(process.env.SARVAM_API_KEY) === undefined)
73
+ add('sarvam-key-unconfigured');
74
+ break;
75
+ case 'gateway': {
76
+ const gateway = settings.providers?.gateway;
77
+ if (trim(gateway?.baseUrl) === undefined && trim(process.env.LITELLM_BASE_URL) === undefined)
78
+ add('gateway-base-url-unconfigured');
79
+ if (trim(gateway?.apiKey) === undefined && trim(process.env.LITELLM_INFERENCE_KEY) === undefined)
80
+ add('gateway-key-unconfigured');
81
+ break;
82
+ }
83
+ case 'openrouter':
84
+ if (trim(settings.providers?.openrouter?.apiKey) === undefined && trim(process.env.OPENROUTER_API_KEY) === undefined)
85
+ add('openrouter-key-unconfigured');
86
+ break;
87
+ case 'cloudflare': {
88
+ const cloudflare = settings.providers?.cloudflare;
89
+ if (trim(cloudflare?.accountId) === undefined && trim(process.env.CLOUDFLARE_ACCOUNT_ID) === undefined)
90
+ add('cloudflare-account-unconfigured');
91
+ if (trim(cloudflare?.apiKey) === undefined && trim(process.env.CLOUDFLARE_API_TOKEN) === undefined)
92
+ add('cloudflare-key-unconfigured');
93
+ if (trim(cloudflare?.gatewayId) === undefined && trim(process.env.CLOUDFLARE_AI_GATEWAY_ID) === undefined)
94
+ add('cloudflare-gateway-unconfigured');
95
+ break;
96
+ }
97
+ }
98
+ return diagnostics;
99
+ }
100
+ const credential = (configured, env) => {
101
+ const value = trim(configured) ?? trim(env);
102
+ if (value === undefined)
103
+ throw new EmbeddingsError('missing-credentials');
104
+ return value;
105
+ };
106
+ const headerCredential = (configured, env) => {
107
+ const value = credential(configured, env);
108
+ if (!headerValueIsSafe(value))
109
+ throw new EmbeddingsError('configuration-invalid');
110
+ return value;
111
+ };
112
+ /** The documented text-string path avoids the token-array schema contradiction without truncating. */
113
+ const openAIPrepare = (encoding, text, signal) => {
114
+ signal.throwIfAborted();
115
+ const prepared = EMBEDDING_DOCUMENT_PREFIX + text;
116
+ const tokens = encoding.encode(prepared, [], []);
117
+ if (tokens.length > OPENAI_MAX_INPUT_TOKENS)
118
+ throw new EmbeddingsError('input-too-long');
119
+ if (encoding.decode(tokens) !== prepared)
120
+ throw new EmbeddingsError('tokenizer-roundtrip-failed');
121
+ return { kind: 'text', text: prepared, tokenCount: tokens.length };
122
+ };
123
+ const preparedTokens = (inputs) => inputs.reduce((sum, input) => sum + (input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0)), 0);
124
+ const providerTexts = (inputs) => inputs.map((input) => {
125
+ if (input.kind !== 'text')
126
+ throw new EmbeddingsError('provider-response-invalid');
127
+ return input.text;
128
+ });
129
+ class OpenAiProvider {
130
+ route = 'openai';
131
+ model = OPENAI_MODEL;
132
+ space = OPENAI_EMBEDDING_SPACE;
133
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
134
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
135
+ #encoding = getEncoding('cl100k_base');
136
+ #key;
137
+ constructor(key) {
138
+ this.#key = key;
139
+ }
140
+ async prepare(text, signal) {
141
+ return openAIPrepare(this.#encoding, text, signal);
142
+ }
143
+ async embed(inputs, signal) {
144
+ const response = await requestJson({
145
+ url: new URL('https://api.openai.com/v1/embeddings'),
146
+ signal,
147
+ headers: { authorization: `Bearer ${this.#key}` },
148
+ body: {
149
+ model: this.model,
150
+ dimensions: this.space.dimensions,
151
+ input: providerTexts(inputs),
152
+ encoding_format: 'float',
153
+ },
154
+ });
155
+ return parseBatchResponse({
156
+ response,
157
+ space: this.space,
158
+ expectedPreparedTokens: preparedTokens(inputs),
159
+ preparedInputTokens: preparedTokens(inputs),
160
+ });
161
+ }
162
+ async close() {
163
+ // js-tiktoken is pure JavaScript and owns no process or handle.
164
+ }
165
+ }
166
+ class SarvamProvider {
167
+ route = 'sarvam';
168
+ model = SARVAM_MODEL;
169
+ space = SARVAM_EMBEDDING_SPACE;
170
+ // The service enforces its documented per-string token estimate and publishes no aggregate cap.
171
+ maxRequestInputs = Number.POSITIVE_INFINITY;
172
+ maxRequestTokens = Number.POSITIVE_INFINITY;
173
+ #key;
174
+ constructor(key) {
175
+ this.#key = key;
176
+ }
177
+ async prepare(text, signal) {
178
+ signal.throwIfAborted();
179
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
180
+ }
181
+ async embed(inputs, signal) {
182
+ const response = await requestJson({
183
+ url: new URL('/v2/embeddings', SARVAM_ORIGIN),
184
+ signal,
185
+ headers: { 'api-subscription-key': this.#key },
186
+ body: { model: this.model, input: providerTexts(inputs), encoding_format: 'float' },
187
+ });
188
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
189
+ }
190
+ async close() {
191
+ // Native fetch owns no long-lived resource.
192
+ }
193
+ }
194
+ class GatewayProvider {
195
+ route = 'gateway';
196
+ model;
197
+ space = OPENAI_EMBEDDING_SPACE;
198
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
199
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
200
+ #encoding = getEncoding('cl100k_base');
201
+ #origin;
202
+ #key;
203
+ #stage;
204
+ constructor(config, origin, key) {
205
+ this.model = config.model;
206
+ this.#origin = origin;
207
+ this.#key = key;
208
+ this.#stage = config.stage;
209
+ }
210
+ async prepare(text, signal) {
211
+ return openAIPrepare(this.#encoding, text, signal);
212
+ }
213
+ async embed(inputs, signal, context) {
214
+ if (context === undefined ||
215
+ !headerValueIsSafe(context.endUser) ||
216
+ context.tags.length === 0 ||
217
+ context.tags.some((tag) => !headerValueIsSafe(tag)))
218
+ throw new EmbeddingsError('attribution-unavailable');
219
+ const response = await requestJson({
220
+ url: new URL('/v1/embeddings', this.#origin),
221
+ signal,
222
+ headers: {
223
+ authorization: `Bearer ${this.#key}`,
224
+ 'x-litellm-customer-id': context.endUser,
225
+ 'x-litellm-tags': context.tags.join(','),
226
+ },
227
+ body: {
228
+ model: this.model,
229
+ dimensions: this.space.dimensions,
230
+ input: providerTexts(inputs),
231
+ encoding_format: 'float',
232
+ },
233
+ });
234
+ const count = preparedTokens(inputs);
235
+ return parseBatchResponse({
236
+ response,
237
+ space: this.space,
238
+ expectedModels: [this.space.model, this.model],
239
+ expectedPreparedTokens: count,
240
+ preparedInputTokens: count,
241
+ });
242
+ }
243
+ async close() {
244
+ // js-tiktoken is pure JavaScript and owns no process or handle.
245
+ }
246
+ }
247
+ class OpenRouterProvider {
248
+ route = 'openrouter';
249
+ model = OPENROUTER_EMBEDDING_MODELS[0];
250
+ space = OPENAI_EMBEDDING_SPACE;
251
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
252
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
253
+ #encoding = getEncoding('cl100k_base');
254
+ #key;
255
+ constructor(key) {
256
+ this.#key = key;
257
+ }
258
+ async prepare(text, signal) {
259
+ return openAIPrepare(this.#encoding, text, signal);
260
+ }
261
+ async embed(inputs, signal) {
262
+ const response = await requestJson({
263
+ url: new URL(OPENROUTER_EMBEDDINGS_URL),
264
+ signal,
265
+ headers: { authorization: `Bearer ${this.#key}` },
266
+ body: {
267
+ model: this.model,
268
+ dimensions: this.space.dimensions,
269
+ input: providerTexts(inputs),
270
+ encoding_format: 'float',
271
+ },
272
+ });
273
+ const count = preparedTokens(inputs);
274
+ return parseBatchResponse({
275
+ response,
276
+ space: this.space,
277
+ expectedModels: [this.model],
278
+ expectedPreparedTokens: count,
279
+ preparedInputTokens: count,
280
+ });
281
+ }
282
+ async close() {
283
+ // js-tiktoken is pure JavaScript and owns no process or handle.
284
+ }
285
+ }
286
+ class CloudflareProvider {
287
+ route = 'cloudflare';
288
+ model = CLOUDFLARE_EMBEDDING_MODELS[0];
289
+ space;
290
+ // Workers AI documents a 512-token input ceiling for this model but no aggregate request cap.
291
+ // The model-owned tokenizer is not available here, so no approximate local cap is invented.
292
+ maxRequestInputs = Number.POSITIVE_INFINITY;
293
+ maxRequestTokens = Number.POSITIVE_INFINITY;
294
+ #url;
295
+ #key;
296
+ #gatewayId;
297
+ #pooling;
298
+ constructor(config) {
299
+ this.#url = new URL(`${CLOUDFLARE_ORIGIN}/${encodeURIComponent(config.accountId)}/ai/run/${config.model}`);
300
+ this.#key = config.apiKey;
301
+ this.#gatewayId = config.gatewayId;
302
+ this.#pooling = config.pooling;
303
+ this.space = cloudflareEmbeddingSpace(config.pooling);
304
+ // The model is pinned from settings; this guard keeps the fixed URL invariant explicit.
305
+ if (config.model !== CLOUDFLARE_EMBEDDING_MODELS[0])
306
+ throw new EmbeddingsError('configuration-invalid');
307
+ }
308
+ async prepare(text, signal) {
309
+ signal.throwIfAborted();
310
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
311
+ }
312
+ async embed(inputs, signal) {
313
+ const response = await requestJson({
314
+ url: this.#url,
315
+ signal,
316
+ headers: {
317
+ authorization: `Bearer ${this.#key}`,
318
+ 'cf-aig-gateway-id': this.#gatewayId,
319
+ },
320
+ body: { text: providerTexts(inputs), pooling: this.#pooling },
321
+ });
322
+ return parseCloudflareBatchResponse({
323
+ response,
324
+ space: this.space,
325
+ expectedCount: inputs.length,
326
+ });
327
+ }
328
+ async close() {
329
+ // Native fetch owns no long-lived resource.
330
+ }
331
+ }
332
+ const noRelease = async () => undefined;
333
+ /** Resolve a configured route only when that route is actually about to be used. */
334
+ export async function acquireProvider({ settings, route, signal, }) {
335
+ switch (route.provider) {
336
+ case 'local': {
337
+ const local = settings.providers?.local;
338
+ const executable = trim(local?.executable);
339
+ const modelPath = trim(local?.modelPath);
340
+ if (local === undefined || executable === undefined || modelPath === undefined)
341
+ throw new EmbeddingsError('configuration-invalid');
342
+ const acquired = await acquireLocalRuntime({ executable, modelPath, port: local.port ?? 8791 }, signal);
343
+ return { provider: acquired.provider, release: acquired.release };
344
+ }
345
+ case 'openai':
346
+ return {
347
+ provider: new OpenAiProvider(credential(settings.providers?.openai?.apiKey, process.env.OPENAI_API_KEY)),
348
+ release: noRelease,
349
+ };
350
+ case 'sarvam':
351
+ return {
352
+ provider: new SarvamProvider(credential(settings.providers?.sarvam?.apiKey, process.env.SARVAM_API_KEY)),
353
+ release: noRelease,
354
+ };
355
+ case 'gateway': {
356
+ const configured = settings.providers?.gateway;
357
+ const baseUrl = trim(configured?.baseUrl) ?? trim(process.env.LITELLM_BASE_URL);
358
+ const key = credential(configured?.apiKey, process.env.LITELLM_INFERENCE_KEY);
359
+ const rawModel = trim(configured?.model) ?? trim(process.env.LITELLM_EMBEDDING_MODEL) ?? OPENAI_MODEL;
360
+ if (rawModel !== 'text-embedding-3-small' &&
361
+ rawModel !== 'openai/text-embedding-3-small')
362
+ throw new EmbeddingsError('configuration-invalid');
363
+ const stage = configured?.stage ?? 'dev';
364
+ if (baseUrl === undefined)
365
+ throw new EmbeddingsError('configuration-invalid');
366
+ const gateway = { baseUrl, apiKey: key, model: rawModel, stage };
367
+ return {
368
+ provider: new GatewayProvider(gateway, fixedOrigin(baseUrl), key),
369
+ release: noRelease,
370
+ };
371
+ }
372
+ case 'openrouter':
373
+ return {
374
+ provider: new OpenRouterProvider(headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)),
375
+ release: noRelease,
376
+ };
377
+ case 'cloudflare': {
378
+ const configured = settings.providers?.cloudflare;
379
+ const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
380
+ const gatewayId = trim(configured?.gatewayId) ?? trim(process.env.CLOUDFLARE_AI_GATEWAY_ID);
381
+ if (accountId === undefined || gatewayId === undefined)
382
+ throw new EmbeddingsError('configuration-invalid');
383
+ if (!headerValueIsSafe(accountId) || !headerValueIsSafe(gatewayId))
384
+ throw new EmbeddingsError('configuration-invalid');
385
+ const model = trim(configured?.model) ?? CLOUDFLARE_EMBEDDING_MODELS[0];
386
+ if (model !== CLOUDFLARE_EMBEDDING_MODELS[0])
387
+ throw new EmbeddingsError('configuration-invalid');
388
+ const pooling = configured?.pooling ?? 'mean';
389
+ return {
390
+ provider: new CloudflareProvider({
391
+ accountId,
392
+ apiKey: headerCredential(configured?.apiKey, process.env.CLOUDFLARE_API_TOKEN),
393
+ gatewayId,
394
+ model,
395
+ pooling,
396
+ }),
397
+ release: noRelease,
398
+ };
399
+ }
400
+ }
401
+ }
402
+ export const spaceForRoute = (route, settings) => {
403
+ switch (route.provider) {
404
+ case 'local':
405
+ return LOCAL_EMBEDDING_SPACE;
406
+ case 'openai':
407
+ case 'gateway':
408
+ case 'openrouter':
409
+ return OPENAI_EMBEDDING_SPACE;
410
+ case 'sarvam':
411
+ return SARVAM_EMBEDDING_SPACE;
412
+ case 'cloudflare':
413
+ return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
414
+ }
415
+ };
@@ -0,0 +1,17 @@
1
+ import type { ProviderBatchResult } from './provider-types.js';
2
+ import type { EmbeddingSpace } from './schemas.js';
3
+ /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
4
+ export declare function normalizeVector(vector: readonly number[], dimensions: number): number[];
5
+ export declare function parseBatchResponse(args: {
6
+ response: unknown;
7
+ space: EmbeddingSpace;
8
+ expectedModels?: readonly string[];
9
+ expectedPreparedTokens?: number | null;
10
+ preparedInputTokens?: number | null;
11
+ }): ProviderBatchResult;
12
+ /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
13
+ export declare function parseCloudflareBatchResponse(args: {
14
+ response: unknown;
15
+ space: EmbeddingSpace;
16
+ expectedCount: number;
17
+ }): ProviderBatchResult;
@@ -0,0 +1,105 @@
1
+ import { Type } from 'typebox';
2
+ import { Value } from 'typebox/value';
3
+ import { EmbeddingsError } from './errors.js';
4
+ const responseSchema = Type.Object({
5
+ model: Type.Optional(Type.String({ minLength: 1 })),
6
+ data: Type.Array(Type.Object({
7
+ index: Type.Integer({ minimum: 0 }),
8
+ embedding: Type.Array(Type.Number()),
9
+ })),
10
+ usage: Type.Object({
11
+ prompt_tokens: Type.Integer({ minimum: 0 }),
12
+ }),
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
+ /** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
20
+ function unwrapCloudflareModelOutput(response) {
21
+ if (typeof response !== 'object' || response === null || Array.isArray(response))
22
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
23
+ const envelope = response;
24
+ if (envelope.success === false ||
25
+ (Array.isArray(envelope.errors) && envelope.errors.length > 0))
26
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
27
+ return Object.hasOwn(envelope, 'result') ? envelope.result : envelope;
28
+ }
29
+ /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
30
+ export function normalizeVector(vector, dimensions) {
31
+ if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
32
+ throw new EmbeddingsError('vector-invalid');
33
+ const scale = vector.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0);
34
+ if (scale === 0)
35
+ throw new EmbeddingsError('vector-zero');
36
+ const norm = Math.sqrt(vector.reduce((sum, value) => sum + (value / scale) ** 2, 0));
37
+ return vector.map((value) => value / scale / norm);
38
+ }
39
+ export function parseBatchResponse(args) {
40
+ const prepared = args.preparedInputTokens ?? args.expectedPreparedTokens ?? null;
41
+ if (!Value.Check(responseSchema, args.response))
42
+ throw new EmbeddingsError('provider-response-invalid', {
43
+ knownUsage: { preparedInputTokens: prepared },
44
+ });
45
+ const parsed = args.response;
46
+ const known = (code) => new EmbeddingsError(code, {
47
+ knownUsage: {
48
+ providerReportedInputTokens: parsed.usage.prompt_tokens,
49
+ preparedInputTokens: prepared,
50
+ },
51
+ });
52
+ const admitted = args.expectedModels ?? [args.space.model];
53
+ if (admitted.length > 0 && (parsed.model === undefined || !admitted.includes(parsed.model)))
54
+ throw known('provider-response-mismatch');
55
+ if (prepared !== null && parsed.usage.prompt_tokens !== prepared)
56
+ throw known('provider-response-mismatch');
57
+ const ordered = [...parsed.data].sort((left, right) => left.index - right.index);
58
+ if (ordered.some((item, index) => item.index !== index))
59
+ throw known('provider-response-mismatch');
60
+ let vectors;
61
+ try {
62
+ vectors = ordered.map((item) => normalizeVector(item.embedding, args.space.dimensions));
63
+ }
64
+ catch (error) {
65
+ if (error instanceof EmbeddingsError)
66
+ throw known(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
67
+ throw error;
68
+ }
69
+ return {
70
+ vectors,
71
+ usage: {
72
+ providerReportedInputTokens: parsed.usage.prompt_tokens,
73
+ preparedInputTokens: prepared,
74
+ billedTokens: null,
75
+ },
76
+ };
77
+ }
78
+ /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
79
+ export function parseCloudflareBatchResponse(args) {
80
+ const output = unwrapCloudflareModelOutput(args.response);
81
+ if (!Value.Check(cloudflareResponseSchema, output))
82
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
83
+ const parsed = output;
84
+ if (parsed.data.length !== args.expectedCount)
85
+ throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
86
+ let vectors;
87
+ try {
88
+ vectors = parsed.data.map((vector) => normalizeVector(vector, args.space.dimensions));
89
+ }
90
+ catch (error) {
91
+ if (error instanceof EmbeddingsError)
92
+ throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
93
+ knownUsage: {},
94
+ });
95
+ throw error;
96
+ }
97
+ return {
98
+ vectors,
99
+ usage: {
100
+ providerReportedInputTokens: null,
101
+ preparedInputTokens: null,
102
+ billedTokens: null,
103
+ },
104
+ };
105
+ }