@abhishek944/pi-embeddings 0.2.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 +44 -4
- package/dist/execute.js +20 -2
- package/dist/extension.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/providers.d.ts +5 -1
- package/dist/providers.js +112 -2
- package/dist/response.d.ts +15 -0
- package/dist/response.js +72 -0
- package/dist/schemas.d.ts +317 -22
- package/dist/schemas.js +91 -0
- package/dist/settings-write.js +2 -2
- package/dist/settings.js +6 -1
- package/dist/tool-contracts.d.ts +141 -9
- package/dist/vertex-provider.d.ts +18 -0
- package/dist/vertex-provider.js +139 -0
- package/package.json +9 -2
- package/src/execute.ts +19 -2
- package/src/extension.ts +2 -2
- package/src/index.ts +10 -0
- package/src/providers.ts +138 -1
- package/src/response.ts +84 -0
- package/src/schemas.ts +112 -0
- package/src/settings-write.ts +2 -2
- package/src/settings.ts +6 -0
- package/src/vertex-provider.ts +152 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abhishek944/pi-embeddings",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam and gateway routes, ordered fallback and explicit comparisons.",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam, Gemini, Vertex ADC and gateway routes, ordered fallback and explicit comparisons.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"mcp",
|
|
10
10
|
"openai",
|
|
11
11
|
"sarvam",
|
|
12
|
+
"gemini",
|
|
12
13
|
"embeddinggemma",
|
|
13
14
|
"litellm"
|
|
14
15
|
],
|
|
@@ -65,6 +66,7 @@
|
|
|
65
66
|
"dependencies": {
|
|
66
67
|
"@amaster.ai/pi-shared": "^0.1.10",
|
|
67
68
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
69
|
+
"google-auth-library": "10.9.1",
|
|
68
70
|
"js-tiktoken": "1.0.21"
|
|
69
71
|
},
|
|
70
72
|
"peerDependencies": {
|
|
@@ -81,5 +83,10 @@
|
|
|
81
83
|
"@types/node": "24.19.2",
|
|
82
84
|
"typebox": "1.3.27",
|
|
83
85
|
"typescript": "5.9.3"
|
|
86
|
+
},
|
|
87
|
+
"repository": {
|
|
88
|
+
"type": "git",
|
|
89
|
+
"url": "https://github.com/abhishek944/astack.git",
|
|
90
|
+
"directory": "packages/pi-embeddings"
|
|
84
91
|
}
|
|
85
92
|
}
|
package/src/execute.ts
CHANGED
|
@@ -135,8 +135,25 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
135
135
|
if (args.signal.aborted) outcomes[index] = cancelled(index);
|
|
136
136
|
else {
|
|
137
137
|
const code = codeOf(error);
|
|
138
|
-
|
|
139
|
-
|
|
138
|
+
if (args.allowFallback && isFallbackError(error)) {
|
|
139
|
+
// Preflight HTTP and credential failures follow the same fallback rule as embed failures.
|
|
140
|
+
// The failed index stays pending; successful inputs are never replayed on the next route.
|
|
141
|
+
const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
|
|
142
|
+
attempts.push({
|
|
143
|
+
id: attemptId,
|
|
144
|
+
route: route.provider,
|
|
145
|
+
model: provider.model,
|
|
146
|
+
routeIndex,
|
|
147
|
+
status: 'error',
|
|
148
|
+
usage: null,
|
|
149
|
+
errorCode: code,
|
|
150
|
+
});
|
|
151
|
+
failureByIndex.set(index, { code, attemptId });
|
|
152
|
+
unfinished.push(index);
|
|
153
|
+
} else {
|
|
154
|
+
failureByIndex.set(index, { code, attemptId: null });
|
|
155
|
+
outcomes[index] = { status: 'error', index, code, attemptId: null };
|
|
156
|
+
}
|
|
140
157
|
}
|
|
141
158
|
}
|
|
142
159
|
}
|
package/src/extension.ts
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
createEmbeddingsRuntimeWithDiagnostics,
|
|
10
10
|
type EmbeddingsRuntimeWithDiagnostics,
|
|
11
11
|
} from './runtime.js';
|
|
12
|
-
import {
|
|
12
|
+
import { configuredDefault, loadEmbeddingSettings } from './settings.js';
|
|
13
13
|
import { updateProjectEmbeddingSettings } from './settings-write.js';
|
|
14
14
|
import {
|
|
15
15
|
EMBEDDINGS_SETTINGS_KEY,
|
|
@@ -179,7 +179,7 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
179
179
|
if (command === 'use') {
|
|
180
180
|
if (parts.length !== 3) throw new EmbeddingsError('configuration-invalid');
|
|
181
181
|
const route: EmbeddingRoute = { provider: parts[1] as EmbeddingRoute['provider'], model: parts[2] ?? '' };
|
|
182
|
-
|
|
182
|
+
configuredDefault({ default: route });
|
|
183
183
|
await updateProjectEmbeddingSettings({
|
|
184
184
|
cwd: ctx.cwd,
|
|
185
185
|
projectTrusted: isProjectTrusted(ctx),
|
package/src/index.ts
CHANGED
|
@@ -16,6 +16,14 @@ export {
|
|
|
16
16
|
EMBEDDING_CONTEXT_META_KEY,
|
|
17
17
|
EMBEDDING_ROUTE_IDS,
|
|
18
18
|
GATEWAY_EMBEDDING_MODELS,
|
|
19
|
+
GEMINI_EMBEDDING_MODELS,
|
|
20
|
+
VERTEX_EMBEDDING_LOCATIONS,
|
|
21
|
+
GEMINI_EMBEDDING_MIN_DIMENSIONS,
|
|
22
|
+
GEMINI_EMBEDDING_MAX_DIMENSIONS,
|
|
23
|
+
GEMINI_EMBEDDING_TASK_FORMATS,
|
|
24
|
+
GEMINI_TASK_PREFIXES,
|
|
25
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
26
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
19
27
|
EMBEDDING_ERROR_CODES,
|
|
20
28
|
} from './schemas.js';
|
|
21
29
|
export type {
|
|
@@ -33,4 +41,6 @@ export type {
|
|
|
33
41
|
EmbeddingCompareEntry,
|
|
34
42
|
EmbeddingCompareResult,
|
|
35
43
|
EmbeddingErrorCode,
|
|
44
|
+
GeminiEmbeddingDimension,
|
|
45
|
+
GeminiEmbeddingTaskFormat,
|
|
36
46
|
} from './schemas.js';
|
package/src/providers.ts
CHANGED
|
@@ -1,20 +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,
|
|
7
8
|
CLOUDFLARE_EMBEDDING_MODELS,
|
|
9
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
10
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
11
|
+
GEMINI_EMBEDDING_MODELS,
|
|
12
|
+
GEMINI_TASK_PREFIXES,
|
|
8
13
|
OPENROUTER_EMBEDDING_MODELS,
|
|
9
14
|
type EmbeddingContext,
|
|
10
15
|
type EmbeddingRoute,
|
|
11
16
|
type EmbeddingSettings,
|
|
12
17
|
type EmbeddingSpace,
|
|
18
|
+
type GeminiEmbeddingDimension,
|
|
19
|
+
type GeminiEmbeddingTaskFormat,
|
|
13
20
|
} from './schemas.js';
|
|
14
21
|
import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
|
|
15
22
|
import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
|
|
16
23
|
import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
|
|
17
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
parseBatchResponse,
|
|
26
|
+
parseCloudflareBatchResponse,
|
|
27
|
+
parseGeminiCountTokensResponse,
|
|
28
|
+
parseGeminiEmbeddingResponse,
|
|
29
|
+
} from './response.js';
|
|
18
30
|
|
|
19
31
|
export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
|
|
20
32
|
provider: 'openai',
|
|
@@ -56,11 +68,30 @@ export const cloudflareEmbeddingSpace = (pooling: CloudflarePooling): EmbeddingS
|
|
|
56
68
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
57
69
|
});
|
|
58
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
|
+
|
|
59
88
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
60
89
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
61
90
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
62
91
|
const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
|
|
63
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;
|
|
64
95
|
|
|
65
96
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
66
97
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
@@ -121,6 +152,14 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
|
|
|
121
152
|
add('cloudflare-gateway-unconfigured');
|
|
122
153
|
break;
|
|
123
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;
|
|
124
163
|
}
|
|
125
164
|
return diagnostics;
|
|
126
165
|
}
|
|
@@ -404,6 +443,76 @@ class CloudflareProvider implements EmbeddingsProvider {
|
|
|
404
443
|
}
|
|
405
444
|
}
|
|
406
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
|
+
|
|
407
516
|
export type AcquiredProvider = Readonly<{
|
|
408
517
|
readonly provider: EmbeddingsProvider;
|
|
409
518
|
readonly release: () => Promise<void>;
|
|
@@ -495,6 +604,24 @@ export async function acquireProvider({
|
|
|
495
604
|
release: noRelease,
|
|
496
605
|
};
|
|
497
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
|
+
}
|
|
498
625
|
}
|
|
499
626
|
}
|
|
500
627
|
|
|
@@ -513,5 +640,15 @@ export const spaceForRoute = (
|
|
|
513
640
|
return SARVAM_EMBEDDING_SPACE;
|
|
514
641
|
case 'cloudflare':
|
|
515
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
|
+
});
|
|
516
653
|
}
|
|
517
654
|
};
|
package/src/response.ts
CHANGED
|
@@ -23,6 +23,27 @@ const cloudflareResponseSchema = Type.Object({
|
|
|
23
23
|
pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
|
|
24
24
|
});
|
|
25
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
|
+
|
|
26
47
|
/** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
|
|
27
48
|
function unwrapCloudflareModelOutput(response: unknown): unknown {
|
|
28
49
|
if (typeof response !== 'object' || response === null || Array.isArray(response))
|
|
@@ -92,6 +113,69 @@ export function parseBatchResponse(args: {
|
|
|
92
113
|
};
|
|
93
114
|
}
|
|
94
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
|
+
|
|
95
179
|
/** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
|
|
96
180
|
export function parseCloudflareBatchResponse(args: {
|
|
97
181
|
response: unknown;
|
package/src/schemas.ts
CHANGED
|
@@ -21,6 +21,8 @@ export const EMBEDDING_ROUTE_IDS = [
|
|
|
21
21
|
'gateway',
|
|
22
22
|
'openrouter',
|
|
23
23
|
'cloudflare',
|
|
24
|
+
'gemini',
|
|
25
|
+
'vertex',
|
|
24
26
|
] as const;
|
|
25
27
|
export type EmbeddingRouteId = (typeof EMBEDDING_ROUTE_IDS)[number];
|
|
26
28
|
|
|
@@ -31,6 +33,36 @@ export const GATEWAY_EMBEDDING_MODELS = [
|
|
|
31
33
|
|
|
32
34
|
export const OPENROUTER_EMBEDDING_MODELS = ['openai/text-embedding-3-small'] as const;
|
|
33
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>;
|
|
34
66
|
|
|
35
67
|
const gatewayModelSchema = Type.Union([
|
|
36
68
|
Type.Literal('text-embedding-3-small'),
|
|
@@ -39,6 +71,27 @@ const gatewayModelSchema = Type.Union([
|
|
|
39
71
|
|
|
40
72
|
const openRouterModelSchema = Type.Literal('openai/text-embedding-3-small');
|
|
41
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
|
+
]);
|
|
42
95
|
|
|
43
96
|
const embeddingErrorCodeSchema = Type.Union([
|
|
44
97
|
Type.Literal('configuration-invalid'),
|
|
@@ -104,6 +157,8 @@ const embeddingProviderSchema = Type.Union([
|
|
|
104
157
|
Type.Literal('gateway'),
|
|
105
158
|
Type.Literal('openrouter'),
|
|
106
159
|
Type.Literal('cloudflare'),
|
|
160
|
+
Type.Literal('gemini'),
|
|
161
|
+
Type.Literal('vertex'),
|
|
107
162
|
]);
|
|
108
163
|
|
|
109
164
|
export const embeddingRouteSchema = Type.Object(
|
|
@@ -120,6 +175,26 @@ const spaceCommon = {
|
|
|
120
175
|
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
121
176
|
};
|
|
122
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
|
+
|
|
123
198
|
/**
|
|
124
199
|
* Complete generating-space identity. `provider` is canonical: the gateway route deliberately
|
|
125
200
|
* reports the OpenAI recipe it declares, not its transport alias.
|
|
@@ -161,6 +236,22 @@ export const embeddingSpaceSchema = Type.Union([
|
|
|
161
236
|
},
|
|
162
237
|
{ additionalProperties: false }
|
|
163
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
|
+
),
|
|
164
255
|
Type.Object(
|
|
165
256
|
{
|
|
166
257
|
...spaceCommon,
|
|
@@ -238,6 +329,27 @@ export const embeddingSettingsSchema = Type.Object(
|
|
|
238
329
|
{ additionalProperties: false }
|
|
239
330
|
)
|
|
240
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
|
+
),
|
|
241
353
|
},
|
|
242
354
|
{ additionalProperties: false }
|
|
243
355
|
)
|
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
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
CLOUDFLARE_EMBEDDING_MODELS,
|
|
9
9
|
EMBEDDINGS_SETTINGS_KEY,
|
|
10
10
|
GATEWAY_EMBEDDING_MODELS,
|
|
11
|
+
GEMINI_EMBEDDING_MODELS,
|
|
11
12
|
OPENROUTER_EMBEDDING_MODELS,
|
|
12
13
|
embeddingSettingsSchema,
|
|
13
14
|
type EmbeddingRoute,
|
|
@@ -21,6 +22,8 @@ const MODELS_BY_PROVIDER: Readonly<Record<EmbeddingRoute['provider'], readonly s
|
|
|
21
22
|
gateway: GATEWAY_EMBEDDING_MODELS,
|
|
22
23
|
openrouter: OPENROUTER_EMBEDDING_MODELS,
|
|
23
24
|
cloudflare: CLOUDFLARE_EMBEDDING_MODELS,
|
|
25
|
+
gemini: GEMINI_EMBEDDING_MODELS,
|
|
26
|
+
vertex: GEMINI_EMBEDDING_MODELS,
|
|
24
27
|
};
|
|
25
28
|
|
|
26
29
|
export const isEmbeddingSettings = (value: unknown): value is EmbeddingSettings =>
|
|
@@ -56,6 +59,9 @@ export function validateEmbeddingSettings(value: unknown): EmbeddingSettings {
|
|
|
56
59
|
assertRoute(route, `fallback[${index}]`);
|
|
57
60
|
for (const [index, route] of (value.compare ?? []).entries())
|
|
58
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');
|
|
59
65
|
if (value.version !== undefined && value.version !== 1)
|
|
60
66
|
return configuration('configuration-invalid');
|
|
61
67
|
return value;
|