@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/schemas.ts
CHANGED
|
@@ -8,13 +8,22 @@
|
|
|
8
8
|
import { Type, type Static } from 'typebox';
|
|
9
9
|
|
|
10
10
|
export const EMBEDDINGS_SETTINGS_KEY = 'pi-embeddings';
|
|
11
|
-
export const EMBEDDINGS_PROTOCOL_VERSION =
|
|
11
|
+
export const EMBEDDINGS_PROTOCOL_VERSION = 2;
|
|
12
12
|
export const EMBEDDING_FORMAT_VERSION = 'host-display-attributes-v1';
|
|
13
13
|
export const EMBEDDING_DOCUMENT_PREFIX = 'title: none | text: ';
|
|
14
14
|
export const EMBEDDING_NORMALIZATION_VERSION = 'finite-nonzero-l2-v1';
|
|
15
15
|
export const EMBEDDING_CONTEXT_META_KEY = 'pi-embeddings/context';
|
|
16
16
|
|
|
17
|
-
export const EMBEDDING_ROUTE_IDS = [
|
|
17
|
+
export const EMBEDDING_ROUTE_IDS = [
|
|
18
|
+
'local',
|
|
19
|
+
'openai',
|
|
20
|
+
'sarvam',
|
|
21
|
+
'gateway',
|
|
22
|
+
'openrouter',
|
|
23
|
+
'cloudflare',
|
|
24
|
+
'gemini',
|
|
25
|
+
'vertex',
|
|
26
|
+
] as const;
|
|
18
27
|
export type EmbeddingRouteId = (typeof EMBEDDING_ROUTE_IDS)[number];
|
|
19
28
|
|
|
20
29
|
export const GATEWAY_EMBEDDING_MODELS = [
|
|
@@ -22,11 +31,68 @@ export const GATEWAY_EMBEDDING_MODELS = [
|
|
|
22
31
|
'openai/text-embedding-3-small',
|
|
23
32
|
] as const;
|
|
24
33
|
|
|
34
|
+
export const OPENROUTER_EMBEDDING_MODELS = ['openai/text-embedding-3-small'] as const;
|
|
35
|
+
export const CLOUDFLARE_EMBEDDING_MODELS = ['@cf/baai/bge-base-en-v1.5'] as const;
|
|
36
|
+
export const GEMINI_EMBEDDING_MODELS = ['gemini-embedding-2'] as const;
|
|
37
|
+
export const GEMINI_EMBEDDING_MIN_DIMENSIONS = 128;
|
|
38
|
+
export const GEMINI_EMBEDDING_MAX_DIMENSIONS = 3072;
|
|
39
|
+
export const DEFAULT_GEMINI_DIMENSIONS = 3072;
|
|
40
|
+
export const GEMINI_EMBEDDING_TASK_FORMATS = [
|
|
41
|
+
'retrieval-document',
|
|
42
|
+
'search-query',
|
|
43
|
+
'question-answering',
|
|
44
|
+
'fact-checking',
|
|
45
|
+
'code-retrieval',
|
|
46
|
+
'classification',
|
|
47
|
+
'clustering',
|
|
48
|
+
'sentence-similarity',
|
|
49
|
+
] as const;
|
|
50
|
+
export const DEFAULT_GEMINI_TASK_FORMAT: GeminiEmbeddingTaskFormat = 'retrieval-document';
|
|
51
|
+
|
|
52
|
+
export type GeminiEmbeddingDimension = number;
|
|
53
|
+
export type GeminiEmbeddingTaskFormat = (typeof GEMINI_EMBEDDING_TASK_FORMATS)[number];
|
|
54
|
+
|
|
55
|
+
/** Official Gemini Embedding 2 text task prefixes. `task_type` is not used for this model. */
|
|
56
|
+
export const GEMINI_TASK_PREFIXES = {
|
|
57
|
+
'retrieval-document': 'title: none | text: ',
|
|
58
|
+
'search-query': 'task: search result | query: ',
|
|
59
|
+
'question-answering': 'task: question answering | query: ',
|
|
60
|
+
'fact-checking': 'task: fact checking | query: ',
|
|
61
|
+
'code-retrieval': 'task: code retrieval | query: ',
|
|
62
|
+
classification: 'task: classification | query: ',
|
|
63
|
+
clustering: 'task: clustering | query: ',
|
|
64
|
+
'sentence-similarity': 'task: sentence similarity | query: ',
|
|
65
|
+
} as const satisfies Record<GeminiEmbeddingTaskFormat, string>;
|
|
66
|
+
|
|
25
67
|
const gatewayModelSchema = Type.Union([
|
|
26
68
|
Type.Literal('text-embedding-3-small'),
|
|
27
69
|
Type.Literal('openai/text-embedding-3-small'),
|
|
28
70
|
]);
|
|
29
71
|
|
|
72
|
+
const openRouterModelSchema = Type.Literal('openai/text-embedding-3-small');
|
|
73
|
+
const cloudflareModelSchema = Type.Literal('@cf/baai/bge-base-en-v1.5');
|
|
74
|
+
const geminiModelSchema = Type.Literal(GEMINI_EMBEDDING_MODELS[0]);
|
|
75
|
+
export const VERTEX_EMBEDDING_LOCATIONS = ['us', 'eu', 'global'] as const;
|
|
76
|
+
const vertexLocationSchema = Type.Union([
|
|
77
|
+
Type.Literal('us'),
|
|
78
|
+
Type.Literal('eu'),
|
|
79
|
+
Type.Literal('global'),
|
|
80
|
+
]);
|
|
81
|
+
const geminiDimensionsSchema = Type.Integer({
|
|
82
|
+
minimum: GEMINI_EMBEDDING_MIN_DIMENSIONS,
|
|
83
|
+
maximum: GEMINI_EMBEDDING_MAX_DIMENSIONS,
|
|
84
|
+
});
|
|
85
|
+
const geminiTaskFormatSchema = Type.Union([
|
|
86
|
+
Type.Literal('retrieval-document'),
|
|
87
|
+
Type.Literal('search-query'),
|
|
88
|
+
Type.Literal('question-answering'),
|
|
89
|
+
Type.Literal('fact-checking'),
|
|
90
|
+
Type.Literal('code-retrieval'),
|
|
91
|
+
Type.Literal('classification'),
|
|
92
|
+
Type.Literal('clustering'),
|
|
93
|
+
Type.Literal('sentence-similarity'),
|
|
94
|
+
]);
|
|
95
|
+
|
|
30
96
|
const embeddingErrorCodeSchema = Type.Union([
|
|
31
97
|
Type.Literal('configuration-invalid'),
|
|
32
98
|
Type.Literal('route-unconfigured'),
|
|
@@ -89,6 +155,10 @@ const embeddingProviderSchema = Type.Union([
|
|
|
89
155
|
Type.Literal('openai'),
|
|
90
156
|
Type.Literal('sarvam'),
|
|
91
157
|
Type.Literal('gateway'),
|
|
158
|
+
Type.Literal('openrouter'),
|
|
159
|
+
Type.Literal('cloudflare'),
|
|
160
|
+
Type.Literal('gemini'),
|
|
161
|
+
Type.Literal('vertex'),
|
|
92
162
|
]);
|
|
93
163
|
|
|
94
164
|
export const embeddingRouteSchema = Type.Object(
|
|
@@ -105,6 +175,26 @@ const spaceCommon = {
|
|
|
105
175
|
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
106
176
|
};
|
|
107
177
|
|
|
178
|
+
const geminiSpaceCommon = {
|
|
179
|
+
format: Type.Literal(EMBEDDING_FORMAT_VERSION),
|
|
180
|
+
prefix: Type.Union([
|
|
181
|
+
Type.Literal('title: none | text: '),
|
|
182
|
+
Type.Literal('task: search result | query: '),
|
|
183
|
+
Type.Literal('task: question answering | query: '),
|
|
184
|
+
Type.Literal('task: fact checking | query: '),
|
|
185
|
+
Type.Literal('task: code retrieval | query: '),
|
|
186
|
+
Type.Literal('task: classification | query: '),
|
|
187
|
+
Type.Literal('task: clustering | query: '),
|
|
188
|
+
Type.Literal('task: sentence similarity | query: '),
|
|
189
|
+
]),
|
|
190
|
+
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
191
|
+
model: geminiModelSchema,
|
|
192
|
+
revision: Type.Null(),
|
|
193
|
+
quantization: Type.Null(),
|
|
194
|
+
dimensions: geminiDimensionsSchema,
|
|
195
|
+
taskFormat: geminiTaskFormatSchema,
|
|
196
|
+
};
|
|
197
|
+
|
|
108
198
|
/**
|
|
109
199
|
* Complete generating-space identity. `provider` is canonical: the gateway route deliberately
|
|
110
200
|
* reports the OpenAI recipe it declares, not its transport alias.
|
|
@@ -146,6 +236,35 @@ export const embeddingSpaceSchema = Type.Union([
|
|
|
146
236
|
},
|
|
147
237
|
{ additionalProperties: false }
|
|
148
238
|
),
|
|
239
|
+
Type.Object(
|
|
240
|
+
{
|
|
241
|
+
...geminiSpaceCommon,
|
|
242
|
+
provider: Type.Literal('gemini'),
|
|
243
|
+
runtime: Type.Literal('gemini-api-v1beta'),
|
|
244
|
+
},
|
|
245
|
+
{ additionalProperties: false }
|
|
246
|
+
),
|
|
247
|
+
Type.Object(
|
|
248
|
+
{
|
|
249
|
+
...geminiSpaceCommon,
|
|
250
|
+
provider: Type.Literal('vertex'),
|
|
251
|
+
runtime: Type.Literal('vertex-ai-v1'),
|
|
252
|
+
},
|
|
253
|
+
{ additionalProperties: false }
|
|
254
|
+
),
|
|
255
|
+
Type.Object(
|
|
256
|
+
{
|
|
257
|
+
...spaceCommon,
|
|
258
|
+
provider: Type.Literal('cloudflare'),
|
|
259
|
+
model: cloudflareModelSchema,
|
|
260
|
+
revision: Type.Null(),
|
|
261
|
+
quantization: Type.Null(),
|
|
262
|
+
runtime: Type.Literal('cloudflare-workers-ai'),
|
|
263
|
+
dimensions: Type.Literal(768),
|
|
264
|
+
pooling: Type.Union([Type.Literal('mean'), Type.Literal('cls')]),
|
|
265
|
+
},
|
|
266
|
+
{ additionalProperties: false }
|
|
267
|
+
),
|
|
149
268
|
]);
|
|
150
269
|
|
|
151
270
|
export const embeddingSettingsSchema = Type.Object(
|
|
@@ -190,6 +309,47 @@ export const embeddingSettingsSchema = Type.Object(
|
|
|
190
309
|
{ additionalProperties: false }
|
|
191
310
|
)
|
|
192
311
|
),
|
|
312
|
+
openrouter: Type.Optional(
|
|
313
|
+
Type.Object(
|
|
314
|
+
{ apiKey: Type.Optional(Type.String({ minLength: 1 })) },
|
|
315
|
+
{ additionalProperties: false }
|
|
316
|
+
)
|
|
317
|
+
),
|
|
318
|
+
cloudflare: Type.Optional(
|
|
319
|
+
Type.Object(
|
|
320
|
+
{
|
|
321
|
+
accountId: Type.Optional(Type.String({ minLength: 1 })),
|
|
322
|
+
apiKey: Type.Optional(Type.String({ minLength: 1 })),
|
|
323
|
+
gatewayId: Type.Optional(Type.String({ minLength: 1 })),
|
|
324
|
+
model: Type.Optional(cloudflareModelSchema),
|
|
325
|
+
pooling: Type.Optional(
|
|
326
|
+
Type.Union([Type.Literal('mean'), Type.Literal('cls')])
|
|
327
|
+
),
|
|
328
|
+
},
|
|
329
|
+
{ additionalProperties: false }
|
|
330
|
+
)
|
|
331
|
+
),
|
|
332
|
+
vertex: Type.Optional(
|
|
333
|
+
Type.Object(
|
|
334
|
+
{
|
|
335
|
+
project: Type.String({ minLength: 1, pattern: '^[a-zA-Z0-9_-]+$' }),
|
|
336
|
+
location: vertexLocationSchema,
|
|
337
|
+
dimensions: geminiDimensionsSchema,
|
|
338
|
+
taskFormat: geminiTaskFormatSchema,
|
|
339
|
+
},
|
|
340
|
+
{ additionalProperties: false }
|
|
341
|
+
)
|
|
342
|
+
),
|
|
343
|
+
gemini: Type.Optional(
|
|
344
|
+
Type.Object(
|
|
345
|
+
{
|
|
346
|
+
apiKey: Type.Optional(Type.String({ minLength: 1 })),
|
|
347
|
+
dimensions: Type.Optional(geminiDimensionsSchema),
|
|
348
|
+
taskFormat: Type.Optional(geminiTaskFormatSchema),
|
|
349
|
+
},
|
|
350
|
+
{ additionalProperties: false }
|
|
351
|
+
)
|
|
352
|
+
),
|
|
193
353
|
},
|
|
194
354
|
{ additionalProperties: false }
|
|
195
355
|
)
|
|
@@ -262,9 +422,26 @@ const errorOutcomeSchema = Type.Object(
|
|
|
262
422
|
|
|
263
423
|
export const embeddingOutcomeSchema = Type.Union([successOutcomeSchema, errorOutcomeSchema]);
|
|
264
424
|
|
|
425
|
+
/**
|
|
426
|
+
* Actual generating identity observed on successful outcomes. `generations` is the complete set;
|
|
427
|
+
* the singular fields are populated only when every successful vector came from one generation.
|
|
428
|
+
*/
|
|
429
|
+
export const embeddingGenerationSchema = Type.Object(
|
|
430
|
+
{
|
|
431
|
+
provider: embeddingProviderSchema,
|
|
432
|
+
model: Type.String({ minLength: 1 }),
|
|
433
|
+
space: embeddingSpaceSchema,
|
|
434
|
+
},
|
|
435
|
+
{ additionalProperties: false }
|
|
436
|
+
);
|
|
437
|
+
|
|
265
438
|
export const embeddingResultSchema = Type.Object(
|
|
266
439
|
{
|
|
267
440
|
schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
|
|
441
|
+
provider: Type.Union([embeddingProviderSchema, Type.Null()]),
|
|
442
|
+
model: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
|
|
443
|
+
space: Type.Union([embeddingSpaceSchema, Type.Null()]),
|
|
444
|
+
generations: Type.Array(embeddingGenerationSchema),
|
|
268
445
|
outcomes: Type.Array(embeddingOutcomeSchema),
|
|
269
446
|
attempts: Type.Array(embeddingAttemptSchema),
|
|
270
447
|
},
|
|
@@ -289,28 +466,6 @@ export const embeddingCompareResultSchema = Type.Object(
|
|
|
289
466
|
{ additionalProperties: false }
|
|
290
467
|
);
|
|
291
468
|
|
|
292
|
-
export const embeddingDiagnosticSchema = Type.Object(
|
|
293
|
-
{
|
|
294
|
-
code: Type.String({ minLength: 1 }),
|
|
295
|
-
severity: Type.Union([Type.Literal('error'), Type.Literal('warning'), Type.Literal('info')]),
|
|
296
|
-
},
|
|
297
|
-
{ additionalProperties: false }
|
|
298
|
-
);
|
|
299
|
-
|
|
300
|
-
export const embeddingDescribeSchema = Type.Object(
|
|
301
|
-
{
|
|
302
|
-
schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
|
|
303
|
-
ready: Type.Boolean(),
|
|
304
|
-
selected: embeddingRouteSchema,
|
|
305
|
-
space: Type.Union([embeddingSpaceSchema, Type.Null()]),
|
|
306
|
-
default: embeddingRouteSchema,
|
|
307
|
-
fallback: Type.Array(embeddingRouteSchema),
|
|
308
|
-
compare: Type.Array(embeddingRouteSchema),
|
|
309
|
-
diagnostics: Type.Array(embeddingDiagnosticSchema),
|
|
310
|
-
},
|
|
311
|
-
{ additionalProperties: false }
|
|
312
|
-
);
|
|
313
|
-
|
|
314
469
|
export type EmbeddingSettings = Static<typeof embeddingSettingsSchema>;
|
|
315
470
|
export type EmbeddingRoute = Static<typeof embeddingRouteSchema>;
|
|
316
471
|
export type EmbeddingSpace = Static<typeof embeddingSpaceSchema>;
|
|
@@ -319,8 +474,7 @@ export type EmbeddingContext = Static<typeof embeddingContextSchema>;
|
|
|
319
474
|
export type EmbeddingUsage = Static<typeof embeddingUsageSchema>;
|
|
320
475
|
export type EmbeddingAttempt = Static<typeof embeddingAttemptSchema>;
|
|
321
476
|
export type EmbeddingOutcome = Static<typeof embeddingOutcomeSchema>;
|
|
477
|
+
export type EmbeddingGeneration = Static<typeof embeddingGenerationSchema>;
|
|
322
478
|
export type EmbeddingResult = Static<typeof embeddingResultSchema>;
|
|
323
479
|
export type EmbeddingCompareEntry = Static<typeof embeddingCompareEntrySchema>;
|
|
324
480
|
export type EmbeddingCompareResult = Static<typeof embeddingCompareResultSchema>;
|
|
325
|
-
export type EmbeddingDiagnostic = Static<typeof embeddingDiagnosticSchema>;
|
|
326
|
-
export type EmbeddingDescribe = Static<typeof embeddingDescribeSchema>;
|
package/src/settings-write.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
3
3
|
import { withFileMutationQueue } from '@earendil-works/pi-coding-agent';
|
|
4
4
|
import { join, resolve } from 'node:path';
|
|
5
|
-
import {
|
|
5
|
+
import { configuredDefault } from './settings.js';
|
|
6
6
|
import { EMBEDDINGS_SETTINGS_KEY, type EmbeddingRoute } from './schemas.js';
|
|
7
7
|
|
|
8
8
|
export class EmbeddingsSettingsWriteError extends Error {}
|
|
@@ -17,7 +17,7 @@ export function updateProjectEmbeddingSettings({
|
|
|
17
17
|
projectTrusted: boolean;
|
|
18
18
|
route: EmbeddingRoute;
|
|
19
19
|
}): Promise<void> {
|
|
20
|
-
|
|
20
|
+
configuredDefault({ default: route });
|
|
21
21
|
const settingsPath = resolve(cwd, '.pi', 'settings.json');
|
|
22
22
|
return withFileMutationQueue(settingsPath, () =>
|
|
23
23
|
updateProjectEmbeddingSettingsNow({ cwd, projectTrusted, route })
|
package/src/settings.ts
CHANGED
|
@@ -5,8 +5,11 @@ import { loadPiSettings, resolveConfigDir } from '@amaster.ai/pi-shared/settings
|
|
|
5
5
|
import { Value } from 'typebox/value';
|
|
6
6
|
import { EmbeddingsError } from './errors.js';
|
|
7
7
|
import {
|
|
8
|
+
CLOUDFLARE_EMBEDDING_MODELS,
|
|
8
9
|
EMBEDDINGS_SETTINGS_KEY,
|
|
9
10
|
GATEWAY_EMBEDDING_MODELS,
|
|
11
|
+
GEMINI_EMBEDDING_MODELS,
|
|
12
|
+
OPENROUTER_EMBEDDING_MODELS,
|
|
10
13
|
embeddingSettingsSchema,
|
|
11
14
|
type EmbeddingRoute,
|
|
12
15
|
type EmbeddingSettings,
|
|
@@ -17,6 +20,10 @@ const MODELS_BY_PROVIDER: Readonly<Record<EmbeddingRoute['provider'], readonly s
|
|
|
17
20
|
openai: ['text-embedding-3-small'],
|
|
18
21
|
sarvam: ['embeddinggemma-2'],
|
|
19
22
|
gateway: GATEWAY_EMBEDDING_MODELS,
|
|
23
|
+
openrouter: OPENROUTER_EMBEDDING_MODELS,
|
|
24
|
+
cloudflare: CLOUDFLARE_EMBEDDING_MODELS,
|
|
25
|
+
gemini: GEMINI_EMBEDDING_MODELS,
|
|
26
|
+
vertex: GEMINI_EMBEDDING_MODELS,
|
|
20
27
|
};
|
|
21
28
|
|
|
22
29
|
export const isEmbeddingSettings = (value: unknown): value is EmbeddingSettings =>
|
|
@@ -52,6 +59,9 @@ export function validateEmbeddingSettings(value: unknown): EmbeddingSettings {
|
|
|
52
59
|
assertRoute(route, `fallback[${index}]`);
|
|
53
60
|
for (const [index, route] of (value.compare ?? []).entries())
|
|
54
61
|
assertRoute(route, `compare[${index}]`);
|
|
62
|
+
const routes = [value.default, ...(value.fallback ?? []), ...(value.compare ?? [])];
|
|
63
|
+
if (routes.some((route) => route.provider === 'vertex') && value.providers?.vertex === undefined)
|
|
64
|
+
return configuration('configuration-invalid');
|
|
55
65
|
if (value.version !== undefined && value.version !== 1)
|
|
56
66
|
return configuration('configuration-invalid');
|
|
57
67
|
return value;
|
package/src/tool-contracts.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { Type } from 'typebox';
|
|
2
1
|
import {
|
|
3
|
-
embeddingDescribeSchema,
|
|
4
2
|
embeddingCompareResultSchema,
|
|
5
3
|
embeddingRequestSchema,
|
|
6
4
|
embeddingResultSchema,
|
|
@@ -8,7 +6,6 @@ import {
|
|
|
8
6
|
|
|
9
7
|
export const EMBED_TOOL = 'embed';
|
|
10
8
|
export const EMBED_COMPARE_TOOL = 'embed_compare';
|
|
11
|
-
export const EMBEDDINGS_DESCRIBE_TOOL = 'embeddings_describe';
|
|
12
9
|
|
|
13
10
|
export const EMBED_TOOL_DESCRIPTION =
|
|
14
11
|
'Embed one or more text inputs with the server-configured embedding route. Provider, model, fallback routes and credentials stay in trusted settings; this tool cannot override them. Returns vectors and their actual generating space as structured data. Full text is preserved; the package owns prefixing and provider batching. Use embed_compare only for an explicit comparison.';
|
|
@@ -16,19 +13,10 @@ export const EMBED_TOOL_DESCRIPTION =
|
|
|
16
13
|
export const EMBED_COMPARE_TOOL_DESCRIPTION =
|
|
17
14
|
'Explicitly compare the same text inputs using exactly the configured compare routes. Every entry is a separate request and may incur charges. No implicit default, fallback, ranking or settings mutation.';
|
|
18
15
|
|
|
19
|
-
export const EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION =
|
|
20
|
-
'Report the selected configured embedding route, generating space and provider-free readiness diagnostics without inference or credentials. Information is not a reservation or a caller storage policy.';
|
|
21
|
-
|
|
22
16
|
export const embedParameters = embeddingRequestSchema;
|
|
23
17
|
export const embedCompareParameters = embeddingRequestSchema;
|
|
24
|
-
export const embeddingsDescribeParameters = Type.Object({}, { additionalProperties: false });
|
|
25
18
|
|
|
26
19
|
export const embedOutput = embeddingResultSchema;
|
|
27
20
|
export const embedCompareOutput = embeddingCompareResultSchema;
|
|
28
|
-
export const embeddingsDescribeOutput = embeddingDescribeSchema;
|
|
29
21
|
|
|
30
|
-
export const EMBEDDINGS_TOOL_NAMES = [
|
|
31
|
-
EMBED_TOOL,
|
|
32
|
-
EMBED_COMPARE_TOOL,
|
|
33
|
-
EMBEDDINGS_DESCRIBE_TOOL,
|
|
34
|
-
] as const;
|
|
22
|
+
export const EMBEDDINGS_TOOL_NAMES = [EMBED_TOOL, EMBED_COMPARE_TOOL] as const;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { GdchClient, GoogleAuth, JWT } from 'google-auth-library';
|
|
2
|
+
import { EmbeddingsError } from './errors.js';
|
|
3
|
+
import { headerValueIsSafe, requestJson } from './provider-http.js';
|
|
4
|
+
import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
|
|
5
|
+
import { parseGeminiCountTokensResponse, parseVertexEmbeddingResponse } from './response.js';
|
|
6
|
+
import {
|
|
7
|
+
EMBEDDING_FORMAT_VERSION,
|
|
8
|
+
EMBEDDING_NORMALIZATION_VERSION,
|
|
9
|
+
GEMINI_EMBEDDING_MODELS,
|
|
10
|
+
GEMINI_TASK_PREFIXES,
|
|
11
|
+
type EmbeddingSettings,
|
|
12
|
+
type EmbeddingSpace,
|
|
13
|
+
} from './schemas.js';
|
|
14
|
+
|
|
15
|
+
type VertexSettings = NonNullable<NonNullable<EmbeddingSettings['providers']>['vertex']>;
|
|
16
|
+
// Gemini Embedding 2 shares an 8192-token window across modalities; excess input is silently truncated.
|
|
17
|
+
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings
|
|
18
|
+
const MAX_INPUT_TOKENS = 8192;
|
|
19
|
+
|
|
20
|
+
export const vertexEmbeddingSpace = (config: VertexSettings): EmbeddingSpace => Object.freeze({
|
|
21
|
+
provider: 'vertex',
|
|
22
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
23
|
+
revision: null,
|
|
24
|
+
quantization: null,
|
|
25
|
+
runtime: 'vertex-ai-v1',
|
|
26
|
+
dimensions: config.dimensions,
|
|
27
|
+
taskFormat: config.taskFormat,
|
|
28
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
29
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
30
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** Inspect only ADC type metadata, including an impersonation source; never expose credentials. */
|
|
34
|
+
const isKeylessCredentialMetadata = (metadata: unknown): boolean => {
|
|
35
|
+
if (typeof metadata !== 'object' || metadata === null || !('type' in metadata)) return false;
|
|
36
|
+
switch (metadata.type) {
|
|
37
|
+
case 'authorized_user':
|
|
38
|
+
case 'external_account':
|
|
39
|
+
case 'external_account_authorized_user':
|
|
40
|
+
return true;
|
|
41
|
+
case 'impersonated_service_account':
|
|
42
|
+
return 'source_credentials' in metadata && isKeylessCredentialMetadata(metadata.source_credentials);
|
|
43
|
+
default:
|
|
44
|
+
// The SDK treats missing/unknown types as JWT credentials too; a denylist misses nested keys.
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Native Vertex transport: fixed Google hosts, explicit resource, keyless ADC, no gcloud or API keys. */
|
|
50
|
+
export class VertexProvider implements EmbeddingsProvider {
|
|
51
|
+
readonly route = 'vertex' as const;
|
|
52
|
+
readonly model = GEMINI_EMBEDDING_MODELS[0];
|
|
53
|
+
readonly space: EmbeddingSpace;
|
|
54
|
+
readonly maxRequestInputs = 1; // embedContent contains exactly one Content.
|
|
55
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
56
|
+
readonly #config: VertexSettings;
|
|
57
|
+
readonly #auth: GoogleAuth;
|
|
58
|
+
readonly #url: URL;
|
|
59
|
+
readonly #countUrl: URL;
|
|
60
|
+
|
|
61
|
+
constructor(config: VertexSettings) {
|
|
62
|
+
this.#config = config;
|
|
63
|
+
this.space = vertexEmbeddingSpace(config);
|
|
64
|
+
const origin = config.location === 'global'
|
|
65
|
+
? 'https://aiplatform.googleapis.com'
|
|
66
|
+
: `https://aiplatform.${config.location}.rep.googleapis.com`;
|
|
67
|
+
const resource = `/v1/projects/${encodeURIComponent(config.project)}/locations/${config.location}/publishers/google/models/${this.model}`;
|
|
68
|
+
this.#url = new URL(`${resource}:embedContent`, origin);
|
|
69
|
+
this.#countUrl = new URL(`${resource}:countTokens`, origin);
|
|
70
|
+
// An explicit project also prevents ADC discovery from invoking gcloud to infer one.
|
|
71
|
+
this.#auth = new GoogleAuth({
|
|
72
|
+
projectId: config.project,
|
|
73
|
+
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async #headers(url: URL, signal: AbortSignal): Promise<Record<string, string>> {
|
|
78
|
+
signal.throwIfAborted();
|
|
79
|
+
let listener: (() => void) | undefined;
|
|
80
|
+
const cancelled = new Promise<never>((_resolve, reject) => {
|
|
81
|
+
listener = () => reject(new EmbeddingsError('cancelled'));
|
|
82
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
83
|
+
});
|
|
84
|
+
try {
|
|
85
|
+
// The SDK does not expose an AbortSignal for ADC discovery/refresh. Stop waiting on cancellation;
|
|
86
|
+
// any in-flight SDK refresh may finish, but cannot proceed to a model request after cancellation.
|
|
87
|
+
const headers = await Promise.race([(async () => {
|
|
88
|
+
const client = await this.#auth.getClient();
|
|
89
|
+
if (client instanceof JWT || client instanceof GdchClient ||
|
|
90
|
+
(this.#auth.jsonContent !== null && !isKeylessCredentialMetadata(this.#auth.jsonContent)))
|
|
91
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
92
|
+
signal.throwIfAborted();
|
|
93
|
+
return client.getRequestHeaders(url);
|
|
94
|
+
})(), cancelled]);
|
|
95
|
+
signal.throwIfAborted();
|
|
96
|
+
const authorization = headers.get('authorization');
|
|
97
|
+
if (authorization === null || !authorization.startsWith('Bearer ') || !headerValueIsSafe(authorization))
|
|
98
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
99
|
+
const result: Record<string, string> = { authorization };
|
|
100
|
+
const quotaProject = headers.get('x-goog-user-project');
|
|
101
|
+
if (quotaProject !== null) {
|
|
102
|
+
if (!headerValueIsSafe(quotaProject)) throw new EmbeddingsError('configuration-invalid');
|
|
103
|
+
result['x-goog-user-project'] = quotaProject;
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
} catch {
|
|
107
|
+
// SDK errors may contain sensitive request metadata. Never propagate them or infer a retry/fallback.
|
|
108
|
+
throw new EmbeddingsError(signal.aborted ? 'cancelled' : 'configuration-invalid');
|
|
109
|
+
} finally {
|
|
110
|
+
if (listener !== undefined) signal.removeEventListener('abort', listener);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
115
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#config.taskFormat] + text;
|
|
116
|
+
const response = await requestJson({
|
|
117
|
+
url: this.#countUrl,
|
|
118
|
+
signal,
|
|
119
|
+
headers: await this.#headers(this.#countUrl, signal),
|
|
120
|
+
body: { contents: [{ role: 'user', parts: [{ text: prepared }] }] },
|
|
121
|
+
});
|
|
122
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
123
|
+
if (tokenCount > MAX_INPUT_TOKENS)
|
|
124
|
+
throw new EmbeddingsError('input-too-long', { knownUsage: { preparedInputTokens: tokenCount } });
|
|
125
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
129
|
+
const input = inputs[0];
|
|
130
|
+
if (inputs.length !== 1 || input?.kind !== 'text' || input.tokenCount === null)
|
|
131
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
132
|
+
const response = await requestJson({
|
|
133
|
+
url: this.#url,
|
|
134
|
+
signal,
|
|
135
|
+
headers: await this.#headers(this.#url, signal),
|
|
136
|
+
body: {
|
|
137
|
+
content: { role: 'user', parts: [{ text: input.text }] },
|
|
138
|
+
embedContentConfig: { outputDimensionality: this.space.dimensions },
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
return parseVertexEmbeddingResponse({
|
|
142
|
+
response,
|
|
143
|
+
space: this.space,
|
|
144
|
+
maxInputTokens: MAX_INPUT_TOKENS,
|
|
145
|
+
preparedInputTokens: input.tokenCount,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async close(): Promise<void> {
|
|
150
|
+
// ADC and native fetch own no adapter-created child, timer or listener.
|
|
151
|
+
}
|
|
152
|
+
}
|