@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 CHANGED
@@ -54,15 +54,50 @@ Settings live under the `pi-embeddings` namespace. Pi loading follows global < a
54
54
  "gatewayId": "${CLOUDFLARE_AI_GATEWAY_ID}",
55
55
  "model": "@cf/baai/bge-base-en-v1.5",
56
56
  "pooling": "cls"
57
+ },
58
+ "gemini": {
59
+ "apiKey": "${GEMINI_API_KEY}",
60
+ "dimensions": 3072,
61
+ "taskFormat": "retrieval-document"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ Provider IDs are route identifiers: `local`, `openai`, `sarvam`, `gateway`, `openrouter`, `cloudflare`, `gemini` and `vertex`. Only the declared model pairs are valid. Omitted or empty `fallback` and `compare` lists are inactive. No route is activated by a schema annotation, a present key or existing model files. Credentials and identifiers may also come from `OPENROUTER_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_AI_GATEWAY_ID` and `GEMINI_API_KEY` in the trusted host environment. An environment fallback works only when the MCP process itself receives that variable; a hosted settings file that is copied without environment forwarding must carry `providers.gemini.apiKey` directly.
69
+
70
+ ### Google Cloud Vertex (keyless ADC)
71
+
72
+ Vertex is a separate route, not a Gemini Developer API endpoint override. All four configuration fields are explicit; no API key, credential JSON, token or custom URL is accepted in package settings:
73
+
74
+ ```json
75
+ {
76
+ "pi-embeddings": {
77
+ "version": 1,
78
+ "default": { "provider": "vertex", "model": "gemini-embedding-2" },
79
+ "fallback": [],
80
+ "providers": {
81
+ "vertex": {
82
+ "project": "highsku",
83
+ "location": "us",
84
+ "dimensions": 768,
85
+ "taskFormat": "retrieval-document"
57
86
  }
58
87
  }
59
88
  }
60
89
  }
61
90
  ```
62
91
 
63
- Provider IDs are route identifiers: `local`, `openai`, `sarvam`, `gateway`, `openrouter` and `cloudflare`. Only the declared model pairs are valid. Omitted or empty `fallback` and `compare` lists are inactive. No route is activated by a schema annotation, a present key or existing model files. Credentials and identifiers may also come from `OPENROUTER_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_AI_GATEWAY_ID` in the trusted host environment.
92
+ `location` is `us`, `eu` or `global`, the documented Gemini Embedding 2 locations. The `us` multi-region is not Iowa-only. `dimensions` accepts 128–3072 and `taskFormat` uses the same instruction formats as Gemini below. Selecting a Vertex route without its provider configuration fails validation before inference.
64
93
 
65
- Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, ambiguous network failure, timeout, 5xx or cancellation. Successful inputs are never replayed on another route. Explicit comparison runs exactly the configured compare list in order, without fallback, ranking or default mutation.
94
+ The official `google-auth-library` discovers ADC in the trusted host environment: local user ADC, attached service account metadata, workload/workforce federation or impersonation. Private-key service-account/GDCH credentials, including an impersonation source, are rejected. The adapter never runs `gcloud`, reads the operator's gcloud token cache, accepts a Gemini API key or creates credentials. The runtime identity needs `aiplatform.endpoints.predict` on the target project/model for both operations; API enablement, IAM, quota and billing remain operator responsibilities. No IAM/API change happens automatically. Local ADC is distinct from `gcloud auth login`; configure it through Google's documented [ADC setup](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc) outside this package.
95
+
96
+ Both `countTokens` and `embedContent` use the same Vertex host and full resource path. US uses `https://aiplatform.us.rep.googleapis.com/v1/projects/{project}/locations/us/publishers/google/models/gemini-embedding-2:{method}`; EU uses the corresponding `eu` host; global uses `https://aiplatform.googleapis.com` with `locations/global`. Only the SDK's bearer authorization and optional quota-project header are forwarded. Native model requests reject redirects and have no automatic retry. ADC discovery/refresh errors are sanitized to `configuration-invalid`, not guessed to be fallback-eligible HTTP errors. Cancellation stops waiting for ADC and prevents a subsequent model request; an already-running SDK credential refresh may finish in the background.
97
+
98
+ Provider-free diagnostics validate configuration only: they do not prove ADC, API activation, permissions or live model readiness. A real successful neutral call is required to establish endpoint/counting acceptance for the selected project/location. The generic Vertex countTokens contract is documented, but model-specific support must not be claimed from static schema validation alone.
99
+
100
+ Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429 from route acquisition, provider preparation or embedding. Gemini `countTokens` preflight errors therefore follow the same fallback rule. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, token-count mismatch, ambiguous network failure, timeout, 5xx or cancellation. Successful inputs are never replayed on another route. Explicit comparison runs exactly the configured compare list in order, without fallback, ranking or default mutation.
66
101
 
67
102
  ## Routes and batching
68
103
 
@@ -72,6 +107,9 @@ Ordinary calls use the configured default, then configured fallback in order, ad
72
107
  - `gateway`: the declared OpenAI recipe through LiteLLM. Only `text-embedding-3-small` and `openai/text-embedding-3-small` aliases are supported. One request carries generic host attribution as `x-litellm-customer-id` and `x-litellm-tags`; missing or unsafe attribution refuses before inference.
73
108
  - `openrouter`: `openai/text-embedding-3-small` through `https://openrouter.ai/api/v1/embeddings` with bearer authentication and float output. It shares the OpenAI generating-space descriptor because the declared model, text preparation and normalization are identical.
74
109
  - `cloudflare`: `@cf/baai/bge-base-en-v1.5` through Cloudflare's documented REST `POST /ai/run/{model}`. The Cloudflare API token goes in `Authorization`, and the gateway ID goes in `cf-aig-gateway-id` as Workers AI requires. `pooling` defaults to `mean`; `cls` produces a different generating space and is recorded in the result. The REST API wraps the model output in its standard `result` envelope; the parser also accepts the model's raw `{ shape, data, pooling }` form. Cloudflare reports no local token usage, so usage fields are null.
110
+ - `gemini`: `gemini-embedding-2` through the fixed Gemini API `POST /v1beta/models/gemini-embedding-2:embedContent` endpoint with the `x-goog-api-key` header. `dimensions` accepts the documented 128–3072 range (768, 1536 and 3072 are Google's recommended sizes) and defaults to `3072`. `taskFormat` selects the documented Gemini 2 text prefix (`retrieval-document` by default, plus query and single-input formats); the package does not send `task_type`, which applies only to `gemini-embedding-001`. Each exact prepared prompt is counted with the model's `countTokens` endpoint before a single-input `embedContent` request; inputs over the documented 8192-token boundary fail before inference, and the embed response token count must match the preflight count before a vector is accepted. `autoTruncate: false` is deliberately not sent because the official SDK marks it Enterprise/Vertex-only. The exact dimension, task format and prefix are recorded in the generating space.
111
+
112
+ - `vertex`: Google Cloud `gemini-embedding-2` through the fixed Vertex `v1` `embedContent` and `countTokens` resource methods with keyless ADC. Each exact instruction-prefixed text is counted before inference and must fit the documented 8192-token window; `role: user` is consistent in both operations. Dimensions use `embedContentConfig.outputDimensionality`. The model's `task_type` and `autoTruncate` options are not used. A true response `truncated` flag, mismatched prompt count, missing usage, invalid dimensions or invalid vector fails closed; no truncated vector is accepted. Its complete descriptor has `provider: vertex` and `runtime: vertex-ai-v1`, distinct from `gemini` even for identical model names and dimensions.
75
113
 
76
114
  The package supplies the document prefix `title: none | text: ` exactly once and normalizes vectors with the recorded stable L2 identity. It never summarizes, trims, chunks or truncates input text.
77
115
 
@@ -87,12 +125,14 @@ This is attribution only. The authenticated server-to-server boundary supplies c
87
125
 
88
126
  ## Generating spaces
89
127
 
90
- Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local, Sarvam and Cloudflare remain distinct at 768 dimensions, and Cloudflare `mean` and `cls` are distinct spaces. Direct OpenAI, the declared gateway alias and the declared OpenRouter alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs, account IDs and gateway IDs are route metadata, not implicit new spaces. The ordinary embed result carries these descriptors for actual successful work; no separate metadata call is required.
128
+ Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local, Sarvam and Cloudflare remain distinct at 768 dimensions, and Cloudflare `mean` and `cls` are distinct spaces. Gemini and Vertex dimensions and task formats are distinct spaces, including 768-dimensional MRL output; Vertex is never relabeled as the Developer API or vice versa, because the provider, prompt format and normalization provenance differ. Direct OpenAI, the declared gateway alias and the declared OpenRouter alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs, account IDs and gateway IDs are route metadata, not implicit new spaces. The ordinary embed result carries these descriptors for actual successful work; no separate metadata call is required.
91
129
 
92
130
  Existing stored vector documents are preserved. Package outcome descriptors allow callers to compare complete identity before persistence; a successful inference from an incompatible space is still reported truthfully.
93
131
 
94
132
  ## Limits
95
133
 
96
- No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local and Cloudflare publish no aggregate request cap, so none is invented. Cloudflare documents a 512-token per-input ceiling for `bge-base-en-v1.5`; this package does not ship that model's tokenizer and does not approximate the ceiling locally, so Cloudflare may reject an oversized input. No cost estimator or pricing table is included; unknown provider accounting is reported as null.
134
+ No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local and Cloudflare publish no aggregate request cap, so none is invented. Gemini publishes an 8192-token input boundary and no aggregate request cap; one exact prompt per request is pre-counted with `countTokens`, and a mismatched embed token count fails closed. Cloudflare documents a 512-token per-input ceiling for `bge-base-en-v1.5`; this package does not ship that model's tokenizer and does not approximate the ceiling locally, so Cloudflare may reject an oversized input. No cost estimator or pricing table is included; unknown provider accounting is reported as null.
135
+
136
+ Official Vertex contracts: [embedContent](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.publishers.models/embedContent), [countTokens](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.publishers.models/countTokens), [multimodal model constraints and task instructions](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings), and [ADC discovery order](https://docs.cloud.google.com/docs/authentication/application-default-credentials).
97
137
 
98
138
  The public result protocol is version 2; stored generating-space documents keep their existing descriptor format. Live cloud or local inference, service deployment and shared database writes are not performed by this package.
package/dist/execute.js CHANGED
@@ -105,8 +105,26 @@ export async function executeEmbeddings(args) {
105
105
  outcomes[index] = cancelled(index);
106
106
  else {
107
107
  const code = codeOf(error);
108
- failureByIndex.set(index, { code, attemptId: null });
109
- outcomes[index] = { status: 'error', index, code, attemptId: null };
108
+ if (args.allowFallback && isFallbackError(error)) {
109
+ // Preflight HTTP and credential failures follow the same fallback rule as embed failures.
110
+ // The failed index stays pending; successful inputs are never replayed on the next route.
111
+ const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
112
+ attempts.push({
113
+ id: attemptId,
114
+ route: route.provider,
115
+ model: provider.model,
116
+ routeIndex,
117
+ status: 'error',
118
+ usage: null,
119
+ errorCode: code,
120
+ });
121
+ failureByIndex.set(index, { code, attemptId });
122
+ unfinished.push(index);
123
+ }
124
+ else {
125
+ failureByIndex.set(index, { code, attemptId: null });
126
+ outcomes[index] = { status: 'error', index, code, attemptId: null };
127
+ }
110
128
  }
111
129
  }
112
130
  }
package/dist/extension.js CHANGED
@@ -2,7 +2,7 @@ import { isProjectTrusted } from '@amaster.ai/pi-shared/settings';
2
2
  import { defineTool, } from '@earendil-works/pi-coding-agent';
3
3
  import { EmbeddingsError } from './errors.js';
4
4
  import { createEmbeddingsRuntimeWithDiagnostics, } from './runtime.js';
5
- import { loadEmbeddingSettings, validateEmbeddingSettings } from './settings.js';
5
+ import { configuredDefault, loadEmbeddingSettings } from './settings.js';
6
6
  import { updateProjectEmbeddingSettings } from './settings-write.js';
7
7
  import { EMBEDDINGS_SETTINGS_KEY, } from './schemas.js';
8
8
  import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, embedCompareOutput, embedCompareParameters, embedOutput, embedParameters, } from './tool-contracts.js';
@@ -130,7 +130,7 @@ export default function piEmbeddingsExtension(pi) {
130
130
  if (parts.length !== 3)
131
131
  throw new EmbeddingsError('configuration-invalid');
132
132
  const route = { provider: parts[1], model: parts[2] ?? '' };
133
- validateEmbeddingSettings({ default: route });
133
+ configuredDefault({ default: route });
134
134
  await updateProjectEmbeddingSettings({
135
135
  cwd: ctx.cwd,
136
136
  projectTrusted: isProjectTrusted(ctx),
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
2
2
  export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
3
3
  export { EmbeddingsError } from './errors.js';
4
- export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, EMBEDDING_ERROR_CODES, } from './schemas.js';
5
- export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, } from './schemas.js';
4
+ export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, GEMINI_EMBEDDING_MODELS, VERTEX_EMBEDDING_LOCATIONS, GEMINI_EMBEDDING_MIN_DIMENSIONS, GEMINI_EMBEDDING_MAX_DIMENSIONS, GEMINI_EMBEDDING_TASK_FORMATS, GEMINI_TASK_PREFIXES, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, EMBEDDING_ERROR_CODES, } from './schemas.js';
5
+ export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, GeminiEmbeddingDimension, GeminiEmbeddingTaskFormat, } from './schemas.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { createEmbeddingsRuntime } from './runtime.js';
2
2
  export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
3
3
  export { EmbeddingsError } from './errors.js';
4
- export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, EMBEDDING_ERROR_CODES, } from './schemas.js';
4
+ export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, GEMINI_EMBEDDING_MODELS, VERTEX_EMBEDDING_LOCATIONS, GEMINI_EMBEDDING_MIN_DIMENSIONS, GEMINI_EMBEDDING_MAX_DIMENSIONS, GEMINI_EMBEDDING_TASK_FORMATS, GEMINI_TASK_PREFIXES, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, EMBEDDING_ERROR_CODES, } from './schemas.js';
@@ -1,9 +1,13 @@
1
- import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
1
+ import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace, type GeminiEmbeddingDimension, type GeminiEmbeddingTaskFormat } from './schemas.js';
2
2
  import type { EmbeddingsProvider } from './provider-types.js';
3
3
  export declare const OPENAI_EMBEDDING_SPACE: EmbeddingSpace;
4
4
  export declare const SARVAM_EMBEDDING_SPACE: EmbeddingSpace;
5
5
  type CloudflarePooling = 'mean' | 'cls';
6
6
  export declare const cloudflareEmbeddingSpace: (pooling: CloudflarePooling) => EmbeddingSpace;
7
+ export declare const geminiEmbeddingSpace: (config: {
8
+ dimensions: GeminiEmbeddingDimension;
9
+ taskFormat: GeminiEmbeddingTaskFormat;
10
+ }) => EmbeddingSpace;
7
11
  export declare const routeKey: (route: EmbeddingRoute) => string;
8
12
  export type EmbeddingDiagnostic = Readonly<{
9
13
  readonly code: string;
package/dist/providers.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { getEncoding } from 'js-tiktoken';
2
+ import { VertexProvider, vertexEmbeddingSpace } from './vertex-provider.js';
2
3
  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 { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, GEMINI_EMBEDDING_MODELS, GEMINI_TASK_PREFIXES, OPENROUTER_EMBEDDING_MODELS, } from './schemas.js';
4
5
  import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
5
6
  import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
6
- import { parseBatchResponse, parseCloudflareBatchResponse } from './response.js';
7
+ import { parseBatchResponse, parseCloudflareBatchResponse, parseGeminiCountTokensResponse, parseGeminiEmbeddingResponse, } from './response.js';
7
8
  export const OPENAI_EMBEDDING_SPACE = Object.freeze({
8
9
  provider: 'openai',
9
10
  model: 'text-embedding-3-small',
@@ -38,11 +39,25 @@ export const cloudflareEmbeddingSpace = (pooling) => Object.freeze({
38
39
  prefix: EMBEDDING_DOCUMENT_PREFIX,
39
40
  normalization: EMBEDDING_NORMALIZATION_VERSION,
40
41
  });
42
+ export const geminiEmbeddingSpace = (config) => Object.freeze({
43
+ provider: 'gemini',
44
+ model: GEMINI_EMBEDDING_MODELS[0],
45
+ revision: null,
46
+ quantization: null,
47
+ runtime: 'gemini-api-v1beta',
48
+ dimensions: config.dimensions,
49
+ taskFormat: config.taskFormat,
50
+ format: EMBEDDING_FORMAT_VERSION,
51
+ prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
52
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
53
+ });
41
54
  const OPENAI_MODEL = 'text-embedding-3-small';
42
55
  const SARVAM_MODEL = 'embeddinggemma-2';
43
56
  const SARVAM_ORIGIN = 'https://api.sarvam.ai';
44
57
  const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
45
58
  const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
59
+ const GEMINI_ORIGIN = 'https://generativelanguage.googleapis.com';
60
+ const GEMINI_MAX_INPUT_TOKENS = 8192;
46
61
  const OPENAI_MAX_INPUT_TOKENS = 8192;
47
62
  const OPENAI_MAX_REQUEST_INPUTS = 2048;
48
63
  const OPENAI_MAX_REQUEST_TOKENS = 300000;
@@ -94,6 +109,15 @@ export function routeDiagnostics(settings, route) {
94
109
  add('cloudflare-gateway-unconfigured');
95
110
  break;
96
111
  }
112
+ case 'gemini':
113
+ if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
114
+ add('gemini-key-unconfigured');
115
+ break;
116
+ case 'vertex':
117
+ if (settings.providers?.vertex === undefined)
118
+ add('vertex-configuration-unconfigured');
119
+ // Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
120
+ break;
97
121
  }
98
122
  return diagnostics;
99
123
  }
@@ -329,6 +353,65 @@ class CloudflareProvider {
329
353
  // Native fetch owns no long-lived resource.
330
354
  }
331
355
  }
356
+ class GeminiProvider {
357
+ route = 'gemini';
358
+ model = GEMINI_EMBEDDING_MODELS[0];
359
+ space;
360
+ // One exact prepared prompt is counted and embedded per request; no vector is accepted unless the
361
+ // embed response token count equals that preflight count.
362
+ maxRequestInputs = 1;
363
+ maxRequestTokens = Number.POSITIVE_INFINITY;
364
+ #url = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:embedContent`, GEMINI_ORIGIN);
365
+ #countUrl = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:countTokens`, GEMINI_ORIGIN);
366
+ #key;
367
+ #taskFormat;
368
+ constructor(key, config) {
369
+ this.#key = key;
370
+ this.#taskFormat = config.taskFormat;
371
+ this.space = geminiEmbeddingSpace(config);
372
+ }
373
+ async prepare(text, signal) {
374
+ signal.throwIfAborted();
375
+ const prepared = GEMINI_TASK_PREFIXES[this.#taskFormat] + text;
376
+ const response = await requestJson({
377
+ url: this.#countUrl,
378
+ signal,
379
+ headers: { 'x-goog-api-key': this.#key },
380
+ body: { contents: [{ parts: [{ text: prepared }] }] },
381
+ });
382
+ const tokenCount = parseGeminiCountTokensResponse(response);
383
+ if (tokenCount > GEMINI_MAX_INPUT_TOKENS)
384
+ throw new EmbeddingsError('input-too-long', {
385
+ knownUsage: { preparedInputTokens: tokenCount },
386
+ });
387
+ return { kind: 'text', text: prepared, tokenCount };
388
+ }
389
+ async embed(inputs, signal) {
390
+ const text = providerTexts(inputs)[0];
391
+ if (inputs.length !== 1 || text === undefined)
392
+ throw new EmbeddingsError('provider-response-invalid');
393
+ const preparedInputTokens = preparedTokens(inputs);
394
+ const response = await requestJson({
395
+ url: this.#url,
396
+ signal,
397
+ headers: { 'x-goog-api-key': this.#key },
398
+ body: {
399
+ model: `models/${this.model}`,
400
+ content: { parts: [{ text }] },
401
+ output_dimensionality: this.space.dimensions,
402
+ },
403
+ });
404
+ return parseGeminiEmbeddingResponse({
405
+ response,
406
+ space: this.space,
407
+ maxInputTokens: GEMINI_MAX_INPUT_TOKENS,
408
+ preparedInputTokens,
409
+ });
410
+ }
411
+ async close() {
412
+ // Native fetch owns no long-lived resource.
413
+ }
414
+ }
332
415
  const noRelease = async () => undefined;
333
416
  /** Resolve a configured route only when that route is actually about to be used. */
334
417
  export async function acquireProvider({ settings, route, signal, }) {
@@ -397,6 +480,22 @@ export async function acquireProvider({ settings, route, signal, }) {
397
480
  release: noRelease,
398
481
  };
399
482
  }
483
+ case 'vertex': {
484
+ const configured = settings.providers?.vertex;
485
+ if (configured === undefined)
486
+ throw new EmbeddingsError('configuration-invalid');
487
+ return { provider: new VertexProvider(configured), release: noRelease };
488
+ }
489
+ case 'gemini': {
490
+ const configured = settings.providers?.gemini;
491
+ return {
492
+ provider: new GeminiProvider(headerCredential(configured?.apiKey, process.env.GEMINI_API_KEY), {
493
+ dimensions: configured?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
494
+ taskFormat: configured?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
495
+ }),
496
+ release: noRelease,
497
+ };
498
+ }
400
499
  }
401
500
  }
402
501
  export const spaceForRoute = (route, settings) => {
@@ -411,5 +510,16 @@ export const spaceForRoute = (route, settings) => {
411
510
  return SARVAM_EMBEDDING_SPACE;
412
511
  case 'cloudflare':
413
512
  return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
513
+ case 'vertex': {
514
+ const configured = settings?.providers?.vertex;
515
+ if (configured === undefined)
516
+ throw new EmbeddingsError('configuration-invalid');
517
+ return vertexEmbeddingSpace(configured);
518
+ }
519
+ case 'gemini':
520
+ return geminiEmbeddingSpace({
521
+ dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
522
+ taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
523
+ });
414
524
  }
415
525
  };
@@ -1,5 +1,7 @@
1
1
  import type { ProviderBatchResult } from './provider-types.js';
2
2
  import type { EmbeddingSpace } from './schemas.js';
3
+ /** Exact prepared-prompt count from the model's own tokenizer, used before inference. */
4
+ export declare function parseGeminiCountTokensResponse(response: unknown): number;
3
5
  /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
4
6
  export declare function normalizeVector(vector: readonly number[], dimensions: number): number[];
5
7
  export declare function parseBatchResponse(args: {
@@ -9,6 +11,19 @@ export declare function parseBatchResponse(args: {
9
11
  expectedPreparedTokens?: number | null;
10
12
  preparedInputTokens?: number | null;
11
13
  }): ProviderBatchResult;
14
+ /**
15
+ * Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
16
+ * only when that response count matches the exact prepared prompt counted before inference; a mismatch
17
+ * or over-limit count fails closed instead of relying on undocumented truncation semantics.
18
+ */
19
+ export declare function parseGeminiEmbeddingResponse(args: {
20
+ response: unknown;
21
+ space: EmbeddingSpace;
22
+ maxInputTokens: number;
23
+ preparedInputTokens: number;
24
+ }): ProviderBatchResult;
25
+ /** Vertex's explicit truncation flag is checked in addition to the exact preflight token count. */
26
+ export declare function parseVertexEmbeddingResponse(args: Parameters<typeof parseGeminiEmbeddingResponse>[0]): ProviderBatchResult;
12
27
  /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
13
28
  export declare function parseCloudflareBatchResponse(args: {
14
29
  response: unknown;
package/dist/response.js CHANGED
@@ -16,6 +16,23 @@ const cloudflareResponseSchema = Type.Object({
16
16
  data: Type.Array(Type.Array(Type.Number())),
17
17
  pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
18
18
  });
19
+ const geminiEmbeddingResponseSchema = Type.Object({
20
+ embedding: Type.Object({ values: Type.Array(Type.Number()) }),
21
+ usageMetadata: Type.Object({ promptTokenCount: Type.Integer({ minimum: 0 }) }),
22
+ });
23
+ const vertexEmbeddingResponseSchema = Type.Object({
24
+ ...geminiEmbeddingResponseSchema.properties,
25
+ truncated: Type.Optional(Type.Boolean()),
26
+ });
27
+ const geminiCountTokensResponseSchema = Type.Object({
28
+ totalTokens: Type.Integer({ minimum: 0 }),
29
+ });
30
+ /** Exact prepared-prompt count from the model's own tokenizer, used before inference. */
31
+ export function parseGeminiCountTokensResponse(response) {
32
+ if (!Value.Check(geminiCountTokensResponseSchema, response))
33
+ throw new EmbeddingsError('provider-response-invalid');
34
+ return response.totalTokens;
35
+ }
19
36
  /** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
20
37
  function unwrapCloudflareModelOutput(response) {
21
38
  if (typeof response !== 'object' || response === null || Array.isArray(response))
@@ -75,6 +92,61 @@ export function parseBatchResponse(args) {
75
92
  },
76
93
  };
77
94
  }
95
+ /**
96
+ * Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
97
+ * only when that response count matches the exact prepared prompt counted before inference; a mismatch
98
+ * or over-limit count fails closed instead of relying on undocumented truncation semantics.
99
+ */
100
+ export function parseGeminiEmbeddingResponse(args) {
101
+ if (!Value.Check(geminiEmbeddingResponseSchema, args.response))
102
+ throw new EmbeddingsError('provider-response-invalid', {
103
+ knownUsage: { preparedInputTokens: args.preparedInputTokens },
104
+ });
105
+ const parsed = args.response;
106
+ const promptTokens = parsed.usageMetadata.promptTokenCount;
107
+ const knownUsage = {
108
+ providerReportedInputTokens: promptTokens,
109
+ preparedInputTokens: args.preparedInputTokens,
110
+ };
111
+ if (promptTokens !== args.preparedInputTokens)
112
+ throw new EmbeddingsError('provider-response-mismatch', { knownUsage });
113
+ if (promptTokens > args.maxInputTokens)
114
+ throw new EmbeddingsError('input-too-long', { knownUsage });
115
+ let vector;
116
+ try {
117
+ vector = normalizeVector(parsed.embedding.values, args.space.dimensions);
118
+ }
119
+ catch (error) {
120
+ if (error instanceof EmbeddingsError)
121
+ throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
122
+ knownUsage,
123
+ });
124
+ throw error;
125
+ }
126
+ return {
127
+ vectors: [vector],
128
+ usage: {
129
+ providerReportedInputTokens: promptTokens,
130
+ preparedInputTokens: args.preparedInputTokens,
131
+ billedTokens: null,
132
+ },
133
+ };
134
+ }
135
+ /** Vertex's explicit truncation flag is checked in addition to the exact preflight token count. */
136
+ export function parseVertexEmbeddingResponse(args) {
137
+ if (!Value.Check(vertexEmbeddingResponseSchema, args.response))
138
+ throw new EmbeddingsError('provider-response-invalid', {
139
+ knownUsage: { preparedInputTokens: args.preparedInputTokens },
140
+ });
141
+ if (args.response.truncated === true)
142
+ throw new EmbeddingsError('input-too-long', {
143
+ knownUsage: {
144
+ providerReportedInputTokens: args.response.usageMetadata.promptTokenCount,
145
+ preparedInputTokens: args.preparedInputTokens,
146
+ },
147
+ });
148
+ return parseGeminiEmbeddingResponse(args);
149
+ }
78
150
  /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
79
151
  export function parseCloudflareBatchResponse(args) {
80
152
  const output = unwrapCloudflareModelOutput(args.response);