@abhishek944/pi-embeddings 0.2.0 → 0.5.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 +50 -5
- package/dist/execute.js +22 -3
- package/dist/extension.js +25 -7
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/provider-types.d.ts +4 -0
- package/dist/providers.d.ts +17 -4
- package/dist/providers.js +257 -4
- package/dist/response.d.ts +26 -0
- package/dist/response.js +135 -2
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +8 -3
- package/dist/schemas.d.ts +570 -22
- package/dist/schemas.js +156 -0
- package/dist/settings-write.js +2 -2
- package/dist/settings.js +8 -1
- package/dist/tool-contracts.d.ts +261 -9
- package/dist/vertex-provider.d.ts +18 -0
- package/dist/vertex-provider.js +139 -0
- package/package.json +10 -2
- package/src/execute.ts +21 -3
- package/src/extension.ts +45 -7
- package/src/index.ts +16 -0
- package/src/provider-types.ts +7 -0
- package/src/providers.ts +338 -3
- package/src/response.ts +156 -2
- package/src/runtime.ts +25 -6
- package/src/schemas.ts +199 -0
- package/src/settings-write.ts +2 -2
- package/src/settings.ts +10 -0
- package/src/vertex-provider.ts +152 -0
package/README.md
CHANGED
|
@@ -54,15 +54,52 @@ 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
|
+
"opencode": { "apiKey": "${OPENCODE_API_KEY}" },
|
|
64
|
+
"opencode-go": { "apiKey": "${OPENCODE_API_KEY}" }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Provider IDs are route identifiers: `local`, `openai`, `sarvam`, `gateway`, `openrouter`, `cloudflare`, `gemini`, `vertex`, `opencode` and `opencode-go`. 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`, `GEMINI_API_KEY` and `OPENCODE_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 the relevant `providers.<route>.apiKey` directly. In the Pi extension, OpenCode routes can also use the provider key already resolved by Pi through `ModelRegistry.getApiKeyForProvider`; the library and MCP server never read Pi's credential file.
|
|
71
|
+
|
|
72
|
+
### Google Cloud Vertex (keyless ADC)
|
|
73
|
+
|
|
74
|
+
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:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{
|
|
78
|
+
"pi-embeddings": {
|
|
79
|
+
"version": 1,
|
|
80
|
+
"default": { "provider": "vertex", "model": "gemini-embedding-2" },
|
|
81
|
+
"fallback": [],
|
|
82
|
+
"providers": {
|
|
83
|
+
"vertex": {
|
|
84
|
+
"project": "highsku",
|
|
85
|
+
"location": "us",
|
|
86
|
+
"dimensions": 768,
|
|
87
|
+
"taskFormat": "retrieval-document"
|
|
57
88
|
}
|
|
58
89
|
}
|
|
59
90
|
}
|
|
60
91
|
}
|
|
61
92
|
```
|
|
62
93
|
|
|
63
|
-
|
|
94
|
+
`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.
|
|
95
|
+
|
|
96
|
+
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.
|
|
64
97
|
|
|
65
|
-
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
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.
|
|
101
|
+
|
|
102
|
+
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
103
|
|
|
67
104
|
## Routes and batching
|
|
68
105
|
|
|
@@ -72,6 +109,12 @@ Ordinary calls use the configured default, then configured fallback in order, ad
|
|
|
72
109
|
- `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
110
|
- `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
111
|
- `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.
|
|
112
|
+
- `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.
|
|
113
|
+
|
|
114
|
+
- `opencode`: OpenCode Console pay-as-you-go models through the fixed `POST https://opencode.ai/inference/openai/v1/embeddings` endpoint with bearer authentication. Pi calls this catalog OpenCode Zen. The twelve documented embedding model IDs are `text-embedding-3-small`, `text-embedding-3-large`, `gemini-embedding-2`, `gemini-embedding-001`, `codestral-embed`, `mistral-embed`, `cohere-embed-v5-pro`, `cohere-embed-v5-fast`, `voyage-4`, `voyage-code-4`, `qwen3-embedding-8b` and `bge-m3`. No `dimensions` option is guessed; the response's vector length becomes the observed dimension in the actual generating space. An echoed model that differs from the configured model fails closed.
|
|
115
|
+
- `opencode-go`: OpenCode Go subscription through the fixed `POST https://opencode.ai/inference/go/openai/v1/embeddings` endpoint. The documented models are `text-embedding-3-small`, `qwen3-embedding-8b` and `gemini-embedding-2`. Embeddings do not need the chat `x-opencode-session` header; the adapter identifies itself with a `pi-embeddings` user agent. A missing or non-Go key returns HTTP 401 or 403; 403 entitlement failures do not advance fallback. Both OpenCode routes use explicit `providers.opencode.apiKey` or `providers.opencode-go.apiKey`, Pi's stored provider key in the extension, or `OPENCODE_API_KEY`, in that order.
|
|
116
|
+
|
|
117
|
+
- `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
118
|
|
|
76
119
|
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
120
|
|
|
@@ -87,12 +130,14 @@ This is attribution only. The authenticated server-to-server boundary supplies c
|
|
|
87
130
|
|
|
88
131
|
## Generating spaces
|
|
89
132
|
|
|
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.
|
|
133
|
+
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
134
|
|
|
92
|
-
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.
|
|
135
|
+
OpenCode Console and Go are always distinct from direct OpenAI and from each other, even when the model ID is the same: their runtime provenance differs, and bit-for-bit equivalence has not been verified. OpenCode preflight descriptors report `dimensions: null`; a successful outcome records the positive vector length observed in that response. 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
136
|
|
|
94
137
|
## Limits
|
|
95
138
|
|
|
96
|
-
No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local and
|
|
139
|
+
No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local, Cloudflare and OpenCode publish no aggregate request cap, so none is invented. OpenCode requires each input to fit the chosen model's context window; the package does not guess a local tokenizer or dimension ceiling for its multi-model catalog, so the service may reject an oversized input. 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. OpenCode's reported `usage.cost` and Go allowance are billing metadata outside the token-usage protocol and remain null in `billedTokens`.
|
|
140
|
+
|
|
141
|
+
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
142
|
|
|
98
143
|
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
|
-
|
|
109
|
-
|
|
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
|
}
|
|
@@ -145,6 +163,7 @@ export async function executeEmbeddings(args) {
|
|
|
145
163
|
attempt.usage = result.usage;
|
|
146
164
|
if (result.vectors.length !== captured.length)
|
|
147
165
|
throw new EmbeddingsError('provider-response-mismatch');
|
|
166
|
+
const actualSpace = result.space ?? provider.space;
|
|
148
167
|
for (const [offset, entry] of captured.entries()) {
|
|
149
168
|
const vector = result.vectors[offset];
|
|
150
169
|
if (vector === undefined)
|
|
@@ -155,7 +174,7 @@ export async function executeEmbeddings(args) {
|
|
|
155
174
|
vector: [...vector],
|
|
156
175
|
route: route.provider,
|
|
157
176
|
model: provider.model,
|
|
158
|
-
space:
|
|
177
|
+
space: actualSpace,
|
|
159
178
|
attemptId,
|
|
160
179
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
161
180
|
};
|
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 {
|
|
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';
|
|
@@ -13,15 +13,33 @@ const summary = (result) => {
|
|
|
13
13
|
};
|
|
14
14
|
const codeOf = (error) => error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
|
|
15
15
|
const signalOptions = (signal) => signal === undefined ? {} : { signal };
|
|
16
|
+
/** Pi exposes provider keys through ModelRegistry; only nonsecret availability is retained. */
|
|
17
|
+
async function piCredentials(ctx) {
|
|
18
|
+
const opencode = (await ctx.modelRegistry.getApiKeyForProvider('opencode')) !== undefined;
|
|
19
|
+
const go = (await ctx.modelRegistry.getApiKeyForProvider('opencode-go')) !== undefined;
|
|
20
|
+
return {
|
|
21
|
+
available: { opencode, 'opencode-go': go },
|
|
22
|
+
resolver: async (provider) => {
|
|
23
|
+
if (provider === 'opencode' || provider === 'opencode-go')
|
|
24
|
+
return ctx.modelRegistry.getApiKeyForProvider(provider);
|
|
25
|
+
return undefined;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
16
29
|
export default function piEmbeddingsExtension(pi) {
|
|
17
30
|
let settings;
|
|
18
31
|
let runtime;
|
|
19
32
|
let cwd = process.cwd();
|
|
20
|
-
const refresh = async (next, nextCwd
|
|
33
|
+
const refresh = async (next, nextCwd, credentials) => {
|
|
21
34
|
await runtime?.close();
|
|
22
35
|
settings = next;
|
|
23
36
|
cwd = nextCwd;
|
|
24
|
-
runtime = createEmbeddingsRuntimeWithDiagnostics({
|
|
37
|
+
runtime = createEmbeddingsRuntimeWithDiagnostics({
|
|
38
|
+
settings: next,
|
|
39
|
+
cwd: nextCwd,
|
|
40
|
+
credentialResolver: credentials.resolver,
|
|
41
|
+
piCredentialAvailable: credentials.available,
|
|
42
|
+
});
|
|
25
43
|
};
|
|
26
44
|
const currentRuntime = (ctx) => {
|
|
27
45
|
if (runtime === undefined || cwd !== ctx.cwd)
|
|
@@ -29,7 +47,7 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
29
47
|
return runtime;
|
|
30
48
|
};
|
|
31
49
|
pi.on('session_start', async (_event, ctx) => {
|
|
32
|
-
await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
|
|
50
|
+
await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd, await piCredentials(ctx));
|
|
33
51
|
});
|
|
34
52
|
pi.on('session_shutdown', async () => {
|
|
35
53
|
await runtime?.close();
|
|
@@ -122,7 +140,7 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
122
140
|
if (parts.length !== 1)
|
|
123
141
|
throw new EmbeddingsError('configuration-invalid');
|
|
124
142
|
const next = loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx));
|
|
125
|
-
await refresh(next, ctx.cwd);
|
|
143
|
+
await refresh(next, ctx.cwd, await piCredentials(ctx));
|
|
126
144
|
reply(pi, ctx, `${EMBEDDINGS_SETTINGS_KEY} settings reloaded. No inference was run.`);
|
|
127
145
|
return;
|
|
128
146
|
}
|
|
@@ -130,13 +148,13 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
130
148
|
if (parts.length !== 3)
|
|
131
149
|
throw new EmbeddingsError('configuration-invalid');
|
|
132
150
|
const route = { provider: parts[1], model: parts[2] ?? '' };
|
|
133
|
-
|
|
151
|
+
configuredDefault({ default: route });
|
|
134
152
|
await updateProjectEmbeddingSettings({
|
|
135
153
|
cwd: ctx.cwd,
|
|
136
154
|
projectTrusted: isProjectTrusted(ctx),
|
|
137
155
|
route,
|
|
138
156
|
});
|
|
139
|
-
await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
|
|
157
|
+
await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd, await piCredentials(ctx));
|
|
140
158
|
reply(pi, ctx, `Selected ${route.provider}/${route.model} in trusted project settings.`);
|
|
141
159
|
return;
|
|
142
160
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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 {
|
|
5
|
-
export
|
|
4
|
+
export type { EmbeddingCredentialResolver } from './provider-types.js';
|
|
5
|
+
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, OPENCODE_EMBEDDING_MODELS, OPENCODE_GO_EMBEDDING_MODELS, 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';
|
|
6
|
+
export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, GeminiEmbeddingDimension, GeminiEmbeddingTaskFormat, OpenCodeRouteId, OpenCodeEmbeddingModel, OpenCodeGoEmbeddingModel, } 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, OPENCODE_EMBEDDING_MODELS, OPENCODE_GO_EMBEDDING_MODELS, 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';
|
package/dist/provider-types.d.ts
CHANGED
|
@@ -16,7 +16,11 @@ export type ProviderUsage = Readonly<{
|
|
|
16
16
|
export type ProviderBatchResult = Readonly<{
|
|
17
17
|
readonly vectors: readonly (readonly number[])[];
|
|
18
18
|
readonly usage: ProviderUsage;
|
|
19
|
+
/** Set only when the response establishes a more specific space than the preflight descriptor. */
|
|
20
|
+
readonly space?: EmbeddingSpace | undefined;
|
|
19
21
|
}>;
|
|
22
|
+
/** Supplied by hosts with a supported provider-key lookup; never invoked with a secret value. */
|
|
23
|
+
export type EmbeddingCredentialResolver = (provider: EmbeddingRouteId) => Promise<string | undefined>;
|
|
20
24
|
export interface EmbeddingsProvider {
|
|
21
25
|
readonly route: EmbeddingRouteId;
|
|
22
26
|
readonly model: string;
|
package/dist/providers.d.ts
CHANGED
|
@@ -1,25 +1,38 @@
|
|
|
1
|
-
import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
|
|
2
|
-
import type { EmbeddingsProvider } from './provider-types.js';
|
|
1
|
+
import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace, type GeminiEmbeddingDimension, type GeminiEmbeddingTaskFormat, type OpenCodeRouteId } from './schemas.js';
|
|
2
|
+
import type { EmbeddingCredentialResolver, 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;
|
|
11
|
+
export declare const OPENCODE_CONSOLE_EMBEDDINGS_URL = "https://opencode.ai/inference/openai/v1/embeddings";
|
|
12
|
+
export declare const OPENCODE_GO_EMBEDDINGS_URL = "https://opencode.ai/inference/go/openai/v1/embeddings";
|
|
13
|
+
export declare const opencodeEmbeddingSpace: (args: {
|
|
14
|
+
provider: OpenCodeRouteId;
|
|
15
|
+
model: string;
|
|
16
|
+
dimensions: number | null;
|
|
17
|
+
}) => EmbeddingSpace;
|
|
7
18
|
export declare const routeKey: (route: EmbeddingRoute) => string;
|
|
19
|
+
export type OpenCodeCredentialAvailability = Readonly<Partial<Record<OpenCodeRouteId, boolean>>>;
|
|
8
20
|
export type EmbeddingDiagnostic = Readonly<{
|
|
9
21
|
readonly code: string;
|
|
10
22
|
readonly severity: 'error' | 'warning' | 'info';
|
|
11
23
|
}>;
|
|
12
24
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
13
|
-
export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[];
|
|
25
|
+
export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute, piCredentialAvailable?: OpenCodeCredentialAvailability): EmbeddingDiagnostic[];
|
|
14
26
|
export type AcquiredProvider = Readonly<{
|
|
15
27
|
readonly provider: EmbeddingsProvider;
|
|
16
28
|
readonly release: () => Promise<void>;
|
|
17
29
|
}>;
|
|
18
30
|
/** Resolve a configured route only when that route is actually about to be used. */
|
|
19
|
-
export declare function acquireProvider({ settings, route, signal, }: {
|
|
31
|
+
export declare function acquireProvider({ settings, route, signal, credentialResolver, }: {
|
|
20
32
|
settings: EmbeddingSettings;
|
|
21
33
|
route: EmbeddingRoute;
|
|
22
34
|
signal: AbortSignal;
|
|
35
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
23
36
|
}): Promise<AcquiredProvider>;
|
|
24
37
|
export declare const spaceForRoute: (route: EmbeddingRoute, settings?: EmbeddingSettings | undefined) => EmbeddingSpace;
|
|
25
38
|
export {};
|
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, OPENCODE_EMBEDDING_MODELS, OPENCODE_GO_EMBEDDING_MODELS, 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, parseOpenCodeBatchResponse, } from './response.js';
|
|
7
8
|
export const OPENAI_EMBEDDING_SPACE = Object.freeze({
|
|
8
9
|
provider: 'openai',
|
|
9
10
|
model: 'text-embedding-3-small',
|
|
@@ -38,21 +39,69 @@ 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
|
+
});
|
|
54
|
+
export const OPENCODE_CONSOLE_EMBEDDINGS_URL = 'https://opencode.ai/inference/openai/v1/embeddings';
|
|
55
|
+
export const OPENCODE_GO_EMBEDDINGS_URL = 'https://opencode.ai/inference/go/openai/v1/embeddings';
|
|
56
|
+
const OPENCODE_USER_AGENT = 'pi-embeddings';
|
|
41
57
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
42
58
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
43
59
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
44
60
|
const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
|
|
45
61
|
const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
|
|
62
|
+
const GEMINI_ORIGIN = 'https://generativelanguage.googleapis.com';
|
|
63
|
+
const GEMINI_MAX_INPUT_TOKENS = 8192;
|
|
46
64
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
47
65
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
48
66
|
const OPENAI_MAX_REQUEST_TOKENS = 300000;
|
|
67
|
+
const isOneOf = (values, value) => values.some((candidate) => candidate === value);
|
|
68
|
+
export const opencodeEmbeddingSpace = (args) => {
|
|
69
|
+
const common = {
|
|
70
|
+
revision: null,
|
|
71
|
+
quantization: null,
|
|
72
|
+
dimensions: args.dimensions,
|
|
73
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
74
|
+
prefix: EMBEDDING_DOCUMENT_PREFIX,
|
|
75
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
76
|
+
};
|
|
77
|
+
if (args.provider === 'opencode') {
|
|
78
|
+
if (!isOneOf(OPENCODE_EMBEDDING_MODELS, args.model))
|
|
79
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
80
|
+
const space = {
|
|
81
|
+
...common,
|
|
82
|
+
provider: 'opencode',
|
|
83
|
+
model: args.model,
|
|
84
|
+
runtime: 'opencode-console-embeddings-v1',
|
|
85
|
+
};
|
|
86
|
+
return Object.freeze(space);
|
|
87
|
+
}
|
|
88
|
+
if (!isOneOf(OPENCODE_GO_EMBEDDING_MODELS, args.model))
|
|
89
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
90
|
+
const space = {
|
|
91
|
+
...common,
|
|
92
|
+
provider: 'opencode-go',
|
|
93
|
+
model: args.model,
|
|
94
|
+
runtime: 'opencode-go-embeddings-v1',
|
|
95
|
+
};
|
|
96
|
+
return Object.freeze(space);
|
|
97
|
+
};
|
|
49
98
|
const trim = (value) => {
|
|
50
99
|
const trimmed = value?.trim();
|
|
51
100
|
return trimmed === undefined || trimmed === '' ? undefined : trimmed;
|
|
52
101
|
};
|
|
53
102
|
export const routeKey = (route) => `${route.provider}\u0000${route.model}`;
|
|
54
103
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
55
|
-
export function routeDiagnostics(settings, route) {
|
|
104
|
+
export function routeDiagnostics(settings, route, piCredentialAvailable = {}) {
|
|
56
105
|
const diagnostics = [];
|
|
57
106
|
const add = (code, severity = 'error') => {
|
|
58
107
|
diagnostics.push({ code, severity });
|
|
@@ -94,6 +143,27 @@ export function routeDiagnostics(settings, route) {
|
|
|
94
143
|
add('cloudflare-gateway-unconfigured');
|
|
95
144
|
break;
|
|
96
145
|
}
|
|
146
|
+
case 'gemini':
|
|
147
|
+
if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
|
|
148
|
+
add('gemini-key-unconfigured');
|
|
149
|
+
break;
|
|
150
|
+
case 'opencode':
|
|
151
|
+
if (trim(settings.providers?.opencode?.apiKey) === undefined &&
|
|
152
|
+
trim(process.env.OPENCODE_API_KEY) === undefined &&
|
|
153
|
+
piCredentialAvailable.opencode !== true)
|
|
154
|
+
add('opencode-key-unconfigured');
|
|
155
|
+
break;
|
|
156
|
+
case 'opencode-go':
|
|
157
|
+
if (trim(settings.providers?.['opencode-go']?.apiKey) === undefined &&
|
|
158
|
+
trim(process.env.OPENCODE_API_KEY) === undefined &&
|
|
159
|
+
piCredentialAvailable['opencode-go'] !== true)
|
|
160
|
+
add('opencode-go-key-unconfigured');
|
|
161
|
+
break;
|
|
162
|
+
case 'vertex':
|
|
163
|
+
if (settings.providers?.vertex === undefined)
|
|
164
|
+
add('vertex-configuration-unconfigured');
|
|
165
|
+
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
166
|
+
break;
|
|
97
167
|
}
|
|
98
168
|
return diagnostics;
|
|
99
169
|
}
|
|
@@ -109,6 +179,31 @@ const headerCredential = (configured, env) => {
|
|
|
109
179
|
throw new EmbeddingsError('configuration-invalid');
|
|
110
180
|
return value;
|
|
111
181
|
};
|
|
182
|
+
const safeHeaderValue = (value) => {
|
|
183
|
+
if (!headerValueIsSafe(value))
|
|
184
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
185
|
+
return value;
|
|
186
|
+
};
|
|
187
|
+
/** Host-provided provider keys are read only when a route is acquired; errors never carry a value. */
|
|
188
|
+
async function openCodeCredential(args) {
|
|
189
|
+
const configured = args.route === 'opencode'
|
|
190
|
+
? args.settings.providers?.opencode?.apiKey
|
|
191
|
+
: args.settings.providers?.['opencode-go']?.apiKey;
|
|
192
|
+
const explicit = trim(configured);
|
|
193
|
+
if (explicit !== undefined)
|
|
194
|
+
return safeHeaderValue(explicit);
|
|
195
|
+
if (args.resolver !== undefined) {
|
|
196
|
+
try {
|
|
197
|
+
const resolved = trim(await args.resolver(args.route));
|
|
198
|
+
if (resolved !== undefined)
|
|
199
|
+
return safeHeaderValue(resolved);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// A host resolver that cannot supply a key leaves the trusted environment fallback intact.
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return headerCredential(undefined, process.env.OPENCODE_API_KEY);
|
|
206
|
+
}
|
|
112
207
|
/** The documented text-string path avoids the token-array schema contradiction without truncating. */
|
|
113
208
|
const openAIPrepare = (encoding, text, signal) => {
|
|
114
209
|
signal.throwIfAborted();
|
|
@@ -163,6 +258,62 @@ class OpenAiProvider {
|
|
|
163
258
|
// js-tiktoken is pure JavaScript and owns no process or handle.
|
|
164
259
|
}
|
|
165
260
|
}
|
|
261
|
+
class OpenCodeProvider {
|
|
262
|
+
route;
|
|
263
|
+
model;
|
|
264
|
+
space;
|
|
265
|
+
// OpenCode documents per-input context requirements but publishes no aggregate request ceiling.
|
|
266
|
+
maxRequestInputs = Number.POSITIVE_INFINITY;
|
|
267
|
+
maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
268
|
+
#url;
|
|
269
|
+
#key;
|
|
270
|
+
constructor(args) {
|
|
271
|
+
this.route = args.route;
|
|
272
|
+
this.model = args.model;
|
|
273
|
+
this.space = opencodeEmbeddingSpace({
|
|
274
|
+
provider: args.route,
|
|
275
|
+
model: args.model,
|
|
276
|
+
dimensions: null,
|
|
277
|
+
});
|
|
278
|
+
this.#url = args.url;
|
|
279
|
+
this.#key = args.key;
|
|
280
|
+
}
|
|
281
|
+
async prepare(text, signal) {
|
|
282
|
+
signal.throwIfAborted();
|
|
283
|
+
return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
|
|
284
|
+
}
|
|
285
|
+
async embed(inputs, signal) {
|
|
286
|
+
const parsed = parseOpenCodeBatchResponse({
|
|
287
|
+
response: await requestJson({
|
|
288
|
+
url: this.#url,
|
|
289
|
+
signal,
|
|
290
|
+
headers: {
|
|
291
|
+
authorization: `Bearer ${this.#key}`,
|
|
292
|
+
'user-agent': OPENCODE_USER_AGENT,
|
|
293
|
+
},
|
|
294
|
+
body: {
|
|
295
|
+
model: this.model,
|
|
296
|
+
input: providerTexts(inputs),
|
|
297
|
+
encoding_format: 'float',
|
|
298
|
+
},
|
|
299
|
+
}),
|
|
300
|
+
expectedModels: [this.model],
|
|
301
|
+
expectedCount: inputs.length,
|
|
302
|
+
});
|
|
303
|
+
return {
|
|
304
|
+
vectors: parsed.vectors,
|
|
305
|
+
usage: parsed.usage,
|
|
306
|
+
space: opencodeEmbeddingSpace({
|
|
307
|
+
provider: this.route,
|
|
308
|
+
model: this.model,
|
|
309
|
+
dimensions: parsed.dimensions,
|
|
310
|
+
}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
async close() {
|
|
314
|
+
// Native fetch owns no long-lived resource.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
166
317
|
class SarvamProvider {
|
|
167
318
|
route = 'sarvam';
|
|
168
319
|
model = SARVAM_MODEL;
|
|
@@ -329,9 +480,68 @@ class CloudflareProvider {
|
|
|
329
480
|
// Native fetch owns no long-lived resource.
|
|
330
481
|
}
|
|
331
482
|
}
|
|
483
|
+
class GeminiProvider {
|
|
484
|
+
route = 'gemini';
|
|
485
|
+
model = GEMINI_EMBEDDING_MODELS[0];
|
|
486
|
+
space;
|
|
487
|
+
// One exact prepared prompt is counted and embedded per request; no vector is accepted unless the
|
|
488
|
+
// embed response token count equals that preflight count.
|
|
489
|
+
maxRequestInputs = 1;
|
|
490
|
+
maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
491
|
+
#url = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:embedContent`, GEMINI_ORIGIN);
|
|
492
|
+
#countUrl = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:countTokens`, GEMINI_ORIGIN);
|
|
493
|
+
#key;
|
|
494
|
+
#taskFormat;
|
|
495
|
+
constructor(key, config) {
|
|
496
|
+
this.#key = key;
|
|
497
|
+
this.#taskFormat = config.taskFormat;
|
|
498
|
+
this.space = geminiEmbeddingSpace(config);
|
|
499
|
+
}
|
|
500
|
+
async prepare(text, signal) {
|
|
501
|
+
signal.throwIfAborted();
|
|
502
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#taskFormat] + text;
|
|
503
|
+
const response = await requestJson({
|
|
504
|
+
url: this.#countUrl,
|
|
505
|
+
signal,
|
|
506
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
507
|
+
body: { contents: [{ parts: [{ text: prepared }] }] },
|
|
508
|
+
});
|
|
509
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
510
|
+
if (tokenCount > GEMINI_MAX_INPUT_TOKENS)
|
|
511
|
+
throw new EmbeddingsError('input-too-long', {
|
|
512
|
+
knownUsage: { preparedInputTokens: tokenCount },
|
|
513
|
+
});
|
|
514
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
515
|
+
}
|
|
516
|
+
async embed(inputs, signal) {
|
|
517
|
+
const text = providerTexts(inputs)[0];
|
|
518
|
+
if (inputs.length !== 1 || text === undefined)
|
|
519
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
520
|
+
const preparedInputTokens = preparedTokens(inputs);
|
|
521
|
+
const response = await requestJson({
|
|
522
|
+
url: this.#url,
|
|
523
|
+
signal,
|
|
524
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
525
|
+
body: {
|
|
526
|
+
model: `models/${this.model}`,
|
|
527
|
+
content: { parts: [{ text }] },
|
|
528
|
+
output_dimensionality: this.space.dimensions,
|
|
529
|
+
},
|
|
530
|
+
});
|
|
531
|
+
return parseGeminiEmbeddingResponse({
|
|
532
|
+
response,
|
|
533
|
+
space: this.space,
|
|
534
|
+
maxInputTokens: GEMINI_MAX_INPUT_TOKENS,
|
|
535
|
+
preparedInputTokens,
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
async close() {
|
|
539
|
+
// Native fetch owns no long-lived resource.
|
|
540
|
+
}
|
|
541
|
+
}
|
|
332
542
|
const noRelease = async () => undefined;
|
|
333
543
|
/** Resolve a configured route only when that route is actually about to be used. */
|
|
334
|
-
export async function acquireProvider({ settings, route, signal, }) {
|
|
544
|
+
export async function acquireProvider({ settings, route, signal, credentialResolver, }) {
|
|
335
545
|
switch (route.provider) {
|
|
336
546
|
case 'local': {
|
|
337
547
|
const local = settings.providers?.local;
|
|
@@ -397,6 +607,35 @@ export async function acquireProvider({ settings, route, signal, }) {
|
|
|
397
607
|
release: noRelease,
|
|
398
608
|
};
|
|
399
609
|
}
|
|
610
|
+
case 'opencode':
|
|
611
|
+
case 'opencode-go':
|
|
612
|
+
return {
|
|
613
|
+
provider: new OpenCodeProvider({
|
|
614
|
+
route: route.provider,
|
|
615
|
+
model: route.model,
|
|
616
|
+
key: await openCodeCredential({ route: route.provider, settings, resolver: credentialResolver }),
|
|
617
|
+
url: new URL(route.provider === 'opencode'
|
|
618
|
+
? OPENCODE_CONSOLE_EMBEDDINGS_URL
|
|
619
|
+
: OPENCODE_GO_EMBEDDINGS_URL),
|
|
620
|
+
}),
|
|
621
|
+
release: noRelease,
|
|
622
|
+
};
|
|
623
|
+
case 'vertex': {
|
|
624
|
+
const configured = settings.providers?.vertex;
|
|
625
|
+
if (configured === undefined)
|
|
626
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
627
|
+
return { provider: new VertexProvider(configured), release: noRelease };
|
|
628
|
+
}
|
|
629
|
+
case 'gemini': {
|
|
630
|
+
const configured = settings.providers?.gemini;
|
|
631
|
+
return {
|
|
632
|
+
provider: new GeminiProvider(headerCredential(configured?.apiKey, process.env.GEMINI_API_KEY), {
|
|
633
|
+
dimensions: configured?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
634
|
+
taskFormat: configured?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
635
|
+
}),
|
|
636
|
+
release: noRelease,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
400
639
|
}
|
|
401
640
|
}
|
|
402
641
|
export const spaceForRoute = (route, settings) => {
|
|
@@ -411,5 +650,19 @@ export const spaceForRoute = (route, settings) => {
|
|
|
411
650
|
return SARVAM_EMBEDDING_SPACE;
|
|
412
651
|
case 'cloudflare':
|
|
413
652
|
return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
|
|
653
|
+
case 'vertex': {
|
|
654
|
+
const configured = settings?.providers?.vertex;
|
|
655
|
+
if (configured === undefined)
|
|
656
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
657
|
+
return vertexEmbeddingSpace(configured);
|
|
658
|
+
}
|
|
659
|
+
case 'gemini':
|
|
660
|
+
return geminiEmbeddingSpace({
|
|
661
|
+
dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
662
|
+
taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
663
|
+
});
|
|
664
|
+
case 'opencode':
|
|
665
|
+
case 'opencode-go':
|
|
666
|
+
return opencodeEmbeddingSpace({ provider: route.provider, model: route.model, dimensions: null });
|
|
414
667
|
}
|
|
415
668
|
};
|