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