@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
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { GdchClient, GoogleAuth, JWT } from 'google-auth-library';
|
|
2
|
+
import { EmbeddingsError } from './errors.js';
|
|
3
|
+
import { headerValueIsSafe, requestJson } from './provider-http.js';
|
|
4
|
+
import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
|
|
5
|
+
import { parseGeminiCountTokensResponse, parseVertexEmbeddingResponse } from './response.js';
|
|
6
|
+
import {
|
|
7
|
+
EMBEDDING_FORMAT_VERSION,
|
|
8
|
+
EMBEDDING_NORMALIZATION_VERSION,
|
|
9
|
+
GEMINI_EMBEDDING_MODELS,
|
|
10
|
+
GEMINI_TASK_PREFIXES,
|
|
11
|
+
type EmbeddingSettings,
|
|
12
|
+
type EmbeddingSpace,
|
|
13
|
+
} from './schemas.js';
|
|
14
|
+
|
|
15
|
+
type VertexSettings = NonNullable<NonNullable<EmbeddingSettings['providers']>['vertex']>;
|
|
16
|
+
// Gemini Embedding 2 shares an 8192-token window across modalities; excess input is silently truncated.
|
|
17
|
+
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings
|
|
18
|
+
const MAX_INPUT_TOKENS = 8192;
|
|
19
|
+
|
|
20
|
+
export const vertexEmbeddingSpace = (config: VertexSettings): EmbeddingSpace => Object.freeze({
|
|
21
|
+
provider: 'vertex',
|
|
22
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
23
|
+
revision: null,
|
|
24
|
+
quantization: null,
|
|
25
|
+
runtime: 'vertex-ai-v1',
|
|
26
|
+
dimensions: config.dimensions,
|
|
27
|
+
taskFormat: config.taskFormat,
|
|
28
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
29
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
30
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** Inspect only ADC type metadata, including an impersonation source; never expose credentials. */
|
|
34
|
+
const isKeylessCredentialMetadata = (metadata: unknown): boolean => {
|
|
35
|
+
if (typeof metadata !== 'object' || metadata === null || !('type' in metadata)) return false;
|
|
36
|
+
switch (metadata.type) {
|
|
37
|
+
case 'authorized_user':
|
|
38
|
+
case 'external_account':
|
|
39
|
+
case 'external_account_authorized_user':
|
|
40
|
+
return true;
|
|
41
|
+
case 'impersonated_service_account':
|
|
42
|
+
return 'source_credentials' in metadata && isKeylessCredentialMetadata(metadata.source_credentials);
|
|
43
|
+
default:
|
|
44
|
+
// The SDK treats missing/unknown types as JWT credentials too; a denylist misses nested keys.
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Native Vertex transport: fixed Google hosts, explicit resource, keyless ADC, no gcloud or API keys. */
|
|
50
|
+
export class VertexProvider implements EmbeddingsProvider {
|
|
51
|
+
readonly route = 'vertex' as const;
|
|
52
|
+
readonly model = GEMINI_EMBEDDING_MODELS[0];
|
|
53
|
+
readonly space: EmbeddingSpace;
|
|
54
|
+
readonly maxRequestInputs = 1; // embedContent contains exactly one Content.
|
|
55
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
56
|
+
readonly #config: VertexSettings;
|
|
57
|
+
readonly #auth: GoogleAuth;
|
|
58
|
+
readonly #url: URL;
|
|
59
|
+
readonly #countUrl: URL;
|
|
60
|
+
|
|
61
|
+
constructor(config: VertexSettings) {
|
|
62
|
+
this.#config = config;
|
|
63
|
+
this.space = vertexEmbeddingSpace(config);
|
|
64
|
+
const origin = config.location === 'global'
|
|
65
|
+
? 'https://aiplatform.googleapis.com'
|
|
66
|
+
: `https://aiplatform.${config.location}.rep.googleapis.com`;
|
|
67
|
+
const resource = `/v1/projects/${encodeURIComponent(config.project)}/locations/${config.location}/publishers/google/models/${this.model}`;
|
|
68
|
+
this.#url = new URL(`${resource}:embedContent`, origin);
|
|
69
|
+
this.#countUrl = new URL(`${resource}:countTokens`, origin);
|
|
70
|
+
// An explicit project also prevents ADC discovery from invoking gcloud to infer one.
|
|
71
|
+
this.#auth = new GoogleAuth({
|
|
72
|
+
projectId: config.project,
|
|
73
|
+
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async #headers(url: URL, signal: AbortSignal): Promise<Record<string, string>> {
|
|
78
|
+
signal.throwIfAborted();
|
|
79
|
+
let listener: (() => void) | undefined;
|
|
80
|
+
const cancelled = new Promise<never>((_resolve, reject) => {
|
|
81
|
+
listener = () => reject(new EmbeddingsError('cancelled'));
|
|
82
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
83
|
+
});
|
|
84
|
+
try {
|
|
85
|
+
// The SDK does not expose an AbortSignal for ADC discovery/refresh. Stop waiting on cancellation;
|
|
86
|
+
// any in-flight SDK refresh may finish, but cannot proceed to a model request after cancellation.
|
|
87
|
+
const headers = await Promise.race([(async () => {
|
|
88
|
+
const client = await this.#auth.getClient();
|
|
89
|
+
if (client instanceof JWT || client instanceof GdchClient ||
|
|
90
|
+
(this.#auth.jsonContent !== null && !isKeylessCredentialMetadata(this.#auth.jsonContent)))
|
|
91
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
92
|
+
signal.throwIfAborted();
|
|
93
|
+
return client.getRequestHeaders(url);
|
|
94
|
+
})(), cancelled]);
|
|
95
|
+
signal.throwIfAborted();
|
|
96
|
+
const authorization = headers.get('authorization');
|
|
97
|
+
if (authorization === null || !authorization.startsWith('Bearer ') || !headerValueIsSafe(authorization))
|
|
98
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
99
|
+
const result: Record<string, string> = { authorization };
|
|
100
|
+
const quotaProject = headers.get('x-goog-user-project');
|
|
101
|
+
if (quotaProject !== null) {
|
|
102
|
+
if (!headerValueIsSafe(quotaProject)) throw new EmbeddingsError('configuration-invalid');
|
|
103
|
+
result['x-goog-user-project'] = quotaProject;
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
} catch {
|
|
107
|
+
// SDK errors may contain sensitive request metadata. Never propagate them or infer a retry/fallback.
|
|
108
|
+
throw new EmbeddingsError(signal.aborted ? 'cancelled' : 'configuration-invalid');
|
|
109
|
+
} finally {
|
|
110
|
+
if (listener !== undefined) signal.removeEventListener('abort', listener);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
115
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#config.taskFormat] + text;
|
|
116
|
+
const response = await requestJson({
|
|
117
|
+
url: this.#countUrl,
|
|
118
|
+
signal,
|
|
119
|
+
headers: await this.#headers(this.#countUrl, signal),
|
|
120
|
+
body: { contents: [{ role: 'user', parts: [{ text: prepared }] }] },
|
|
121
|
+
});
|
|
122
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
123
|
+
if (tokenCount > MAX_INPUT_TOKENS)
|
|
124
|
+
throw new EmbeddingsError('input-too-long', { knownUsage: { preparedInputTokens: tokenCount } });
|
|
125
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
129
|
+
const input = inputs[0];
|
|
130
|
+
if (inputs.length !== 1 || input?.kind !== 'text' || input.tokenCount === null)
|
|
131
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
132
|
+
const response = await requestJson({
|
|
133
|
+
url: this.#url,
|
|
134
|
+
signal,
|
|
135
|
+
headers: await this.#headers(this.#url, signal),
|
|
136
|
+
body: {
|
|
137
|
+
content: { role: 'user', parts: [{ text: input.text }] },
|
|
138
|
+
embedContentConfig: { outputDimensionality: this.space.dimensions },
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
return parseVertexEmbeddingResponse({
|
|
142
|
+
response,
|
|
143
|
+
space: this.space,
|
|
144
|
+
maxInputTokens: MAX_INPUT_TOKENS,
|
|
145
|
+
preparedInputTokens: input.tokenCount,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async close(): Promise<void> {
|
|
150
|
+
// ADC and native fetch own no adapter-created child, timer or listener.
|
|
151
|
+
}
|
|
152
|
+
}
|