Elffuss BraidHub

kikocis/continue public

Merge pull request #6526 from continuedev/dallin/vertex-openai-adapter

feat: VertexAI keyFile, keyJson, and express/apiKey support
Changeset3b2a154ca2596effa6c1428f214fb2a15782f0d79b6a4af797e062b782f7208f
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-07-09 18:53 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-09 18:53 -07:00
Parentse2f77bfd9263, db864592ad6c

Browse the files at this changeset

2 files changed

modified core/llm/llms/VertexAI.ts +149 −27
@@ -1,4 +1,4 @@
1-import { GoogleAuth } from "google-auth-library";
1+import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
22
33 import { streamResponse, streamSse } from "@continuedev/fetch";
44 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
@@ -14,30 +14,40 @@
1414 declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
1515 declare anthropicInstance: Anthropic;
1616 declare geminiInstance: Gemini;
17+ static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
1718
1819 static defaultOptions: Partial<LLMOptions> | undefined = {
1920 maxEmbeddingBatchSize: 250,
2021 region: "us-central1",
2122 };
2223
23- private clientPromise = new GoogleAuth({
24- scopes: "https://www.googleapis.com/auth/cloud-platform",
25- })
26- .getClient()
27- .catch((e) => {
28- console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
29- });
24+ private clientPromise: Promise<AuthClient | void>;
3025
31- private static getDefaultApiBaseFrom(options: LLMOptions) {
32- const { region, projectId } = options;
33- if (!region || !projectId) {
34- throw new Error(
35- "region and projectId must be defined if apiBase is not provided",
36- );
37- }
38- return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
39- }
26+ /*
27+ Vertex Supports 3 different URL formats
28+ 1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent
29+ 2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent
30+ 3. Express mode: e.g. https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:streamGenerateContent?key={API_KEY} // see https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview
31+
32+ Authentication can be done using the following
33+ 2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region
34+ 1. API Key (express mode), region and projectId will be ignored
4035
36+ In all cases we have defined apiBase to be up to everything including the location.
37+ Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/
38+ Express api base: https://aiplatform.googleapis.com/v1/
39+ TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet
40+
41+ Note that VertexAI uses the term "service endpoint" and "model", like:
42+ {service-endpoint}/v1/{model}:streamGenerateContent
43+ So "model" includes the project, location, publisher, etc
44+
45+ Express mode has limited support
46+ and CRITICALLY is only available to NEW users who had NOT used cloud services before.
47+ However it is pretty common as gemini becomes more popular.
48+ Only Gemini models are supported for now
49+ https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models
50+ */
4151 constructor(_options: LLMOptions) {
4252 if (_options.region !== "us-central1") {
4353 // Any region outside of us-central1 has a max batch size of 5.
@@ -47,7 +57,7 @@
4757 );
4858 }
4959 super(_options);
50- this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
60+
5161 this.vertexProvider =
5262 _options.model.includes("mistral") ||
5363 _options.model.includes("codestral") ||
@@ -58,24 +68,130 @@
5868 : _options.model.includes("gemini")
5969 ? "gemini"
6070 : "unknown";
71+
72+ // Set client authentication promise
73+ const { apiKey, region, projectId, env } = _options;
74+ const keyFile = env?.keyFile;
75+ const keyJson = env?.keyJson;
76+
77+ // Acceptable authentication methods:
78+ // apiKey only
79+ // region and projectId AND (keyFile OR keyJson OR nothing)
80+
81+ if (apiKey) {
82+ // Consider warning here instead of throwing error
83+ if (region || projectId || keyFile || keyJson) {
84+ throw new Error(
85+ "Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson",
86+ );
87+ // console.warn(
88+ // "Region, projectId, and key path/file are ignored when apiKey is set. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview",
89+ // );
90+ }
91+ if (this.vertexProvider !== "gemini") {
92+ throw new Error(
93+ "VertexAI: only gemini models are supported in express (apiKey) mode. See https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models",
94+ );
95+ }
96+ } else {
97+ if (!region && !projectId) {
98+ throw new Error(
99+ "region and projectId are required for VertexAI (when not using express/apiKey mode)",
100+ );
101+ }
102+ if (keyFile && keyJson) {
103+ throw new Error(
104+ "VertexAI credentials can be configured with either keyFile or keyJson but not both",
105+ );
106+ }
107+ }
108+
109+ if (keyJson) {
110+ // Loading keys from manually set JSON
111+ if (typeof keyJson !== "string") {
112+ throw new Error("VertexAI: keyJson must be a JSON string");
113+ }
114+ try {
115+ const parsed = JSON.parse(keyJson);
116+ if (!parsed?.private_key) {
117+ throw new Error("VertexAI: keyJson must contain a valid private key");
118+ }
119+ parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
120+ const jsonClient = auth.fromJSON(parsed);
121+ if (jsonClient instanceof JWT) {
122+ jsonClient.scopes = [VertexAI.AUTH_SCOPES];
123+ } else {
124+ throw new Error("VertexAI: keyJson must be a valid JWT");
125+ }
126+ this.clientPromise = Promise.resolve(jsonClient);
127+ } catch (e) {
128+ throw new Error("VertexAI: Failed to parse keyJson");
129+ }
130+ } else if (keyFile) {
131+ // Loading keys from manually set file path
132+ if (typeof keyFile !== "string") {
133+ throw new Error("VertexAI: keyFile must be a string");
134+ }
135+ this.clientPromise = new GoogleAuth({
136+ scopes: VertexAI.AUTH_SCOPES,
137+ keyFile,
138+ })
139+ .getClient()
140+ .catch((e) => {
141+ console.warn(
142+ `Failed to load credentials for Vertex AI: ${e.message}`,
143+ );
144+ });
145+ } else {
146+ // Loading keys from local credentials or environment variable
147+ this.clientPromise = new GoogleAuth({
148+ scopes: VertexAI.AUTH_SCOPES,
149+ })
150+ .getClient()
151+ .catch((e) => {
152+ console.warn(
153+ `Failed to load credentials for Vertex AI: ${e.message}`,
154+ );
155+ });
156+ }
157+
158+ // Set api base
159+ if (!this.apiBase) {
160+ if (apiKey) {
161+ // Express mode
162+ this.apiBase = `https://aiplatform.googleapis.com/v1/`;
163+ } else {
164+ this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
165+ }
166+ }
167+
168+ // Uses instances of other LLMs since underlying functionality is the same
61169 this.anthropicInstance = new Anthropic(_options);
62170 this.geminiInstance = new Gemini(_options);
63171 }
64172
65- async fetch(url: RequestInfo | URL, init?: RequestInit) {
66- const client = await this.clientPromise;
67- const result = await client?.getAccessToken();
68- if (!result?.token) {
69- throw new Error(
70- "Could not get an access token. Set up your Google Application Default Credentials.",
71- );
173+ async fetch(url: URL, init?: RequestInit) {
174+ const headers: Record<string, string> = {
175+ "Content-Type": "application/json",
176+ };
177+ if (this.apiKey) {
178+ url.searchParams.set("key", this.apiKey);
179+ } else {
180+ const client = await this.clientPromise;
181+ const result = await client?.getAccessToken();
182+ if (!result?.token) {
183+ throw new Error(
184+ "Could not get an access token. Set up your Google Application Default Credentials.",
185+ );
186+ }
187+ headers.Authorization = `Bearer ${result.token}`;
72188 }
189+
73190 return await super.fetch(url, {
74191 ...init,
75192 headers: {
76- "Content-Type": "application/json",
77- Authorization: `Bearer ${result.token}`,
78193 ...init?.headers,
194+ ...headers,
79195 },
80196 });
81197 }
@@ -85,6 +201,10 @@
85201 const convertedArgs = this.anthropicInstance.convertArgs(options);
86202
87203 // Remove the `model` property and add `anthropic_version`
204+ // For claude 4 models
205+ // anthropic_version is a required parameter and must be set to "vertex-2024-10-22".
206+
207+ // const
88208 const { model, ...finalOptions } = convertedArgs;
89209 return {
90210 ...finalOptions,
@@ -104,6 +224,8 @@
104224 this.cacheBehavior?.cacheSystemMessage && systemMessage
105225 );
106226
227+ // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
228+
107229 const apiURL = new URL(
108230 `publishers/anthropic/models/${options.model}:streamRawPredict`,
109231 this.apiBase,
modified docs/docs/customize/model-providers/top-level/vertexai.mdx +30 −0
@@ -114,3 +114,33 @@
114114 Vertex AI currently does not offer any reranking models.
115115
116116 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
117+
118+## Express mode
119+
120+You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now.
121+
122+<Tabs groupId="config-example">
123+ <TabItem value="yaml" label="YAML">
124+ ```yaml title="config.yaml"
125+ models:
126+ - name: Gemini 2.5 Flash - VertexAI
127+ provider: vertexai
128+ model: gemini-2.5-flash
129+ apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }}
130+ ```
131+ </TabItem>
132+ <TabItem value="json" label="JSON">
133+ ```json title="config.json"
134+ {
135+ "models": [
136+ {
137+ "title": "Gemini 2.5 Flash - VertexAI",
138+ "provider": "vertexai",
139+ "model": "gemini-2.5-flash",
140+ "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]",
141+ }
142+ ]
143+ }
144+ ```
145+ </TabItem>
146+</Tabs>