From 094d548954a9b58d067c57d5d585498330ed7e71 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 8 Jul 2025 17:22:18 -0700 Subject: [PATCH 1/4] add apiKey/express mode support for vertex AI --- core/llm/llms/VertexAI.ts | 77 ++++++++++++++++++++++++++++++++------- 1 file changed, 64 insertions(+), 13 deletions(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 1a956cf76..b7a5e7ecf 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -28,11 +28,49 @@ class VertexAI extends BaseLLM { console.warn(`Failed to load credentials for Vertex AI: ${e.message}`); }); - private static getDefaultApiBaseFrom(options: LLMOptions) { - const { region, projectId } = options; + /* + Vertex Supports 3 different URL formats + 1. 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 + 2. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent + 3. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent + + Authentication can be done using the following + 1. API Key (express mode), region and projectId will be ignored + 2. project id and region with Google Auth client + + In all cases we have defined apiBase to be up to everything including the location. + Express api base: https://aiplatform.googleapis.com/v1/ + Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/ + TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet + + Note that VertexAI uses the term "service endpoint" and "model", like: + {service-endpoint}/v1/{model}:streamGenerateContent + So "model" includes the project, location, publisher, etc + + Express mode has limited support + https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models + supported methods: countTokens, generateContent, and streamGenerateContent + supported models: gemini for now (updating quickly) + + */ + private getDefaultApiBaseFrom(options: LLMOptions) { + const { region, projectId, apiKey } = options; + if (apiKey) { + if (this.vertexProvider !== "gemini") { + throw new Error( + "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", + ); + } + if (region || projectId) { + console.warn( + "Region and projectId are ignored when using apiKey. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview", + ); + } + return `https://aiplatform.googleapis.com/v1/`; + } if (!region || !projectId) { throw new Error( - "region and projectId must be defined if apiBase is not provided", + "To authenticate VertexAI, either add your region and projectId, which will Google Cloud credientials, or add an apiKey (express mode)", ); } return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; @@ -47,7 +85,7 @@ class VertexAI extends BaseLLM { ); } super(_options); - this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); + this.apiBase ??= this.getDefaultApiBaseFrom(_options); this.vertexProvider = _options.model.includes("mistral") || _options.model.includes("codestral") || @@ -62,20 +100,27 @@ class VertexAI extends BaseLLM { this.geminiInstance = new Gemini(_options); } - async fetch(url: RequestInfo | URL, init?: RequestInit) { - const client = await this.clientPromise; - const result = await client?.getAccessToken(); - if (!result?.token) { - throw new Error( - "Could not get an access token. Set up your Google Application Default Credentials.", - ); + async fetch(url: URL, init?: RequestInit) { + const headers: Record = { + "Content-Type": "application/json", + }; + if (this.apiKey) { + url.searchParams.set("key", this.apiKey); + } else { + const client = await this.clientPromise; + const result = await client?.getAccessToken(); + if (!result?.token) { + throw new Error( + "Could not get an access token. Set up your Google Application Default Credentials.", + ); + } + headers.Authorization = `Bearer ${result.token}`; } return await super.fetch(url, { ...init, headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${result.token}`, ...init?.headers, + ...headers, }, }); } @@ -85,6 +130,10 @@ class VertexAI extends BaseLLM { const convertedArgs = this.anthropicInstance.convertArgs(options); // Remove the `model` property and add `anthropic_version` + // For claude 4 models + // anthropic_version is a required parameter and must be set to "vertex-2024-10-22". + + // const const { model, ...finalOptions } = convertedArgs; return { ...finalOptions, @@ -104,6 +153,8 @@ class VertexAI extends BaseLLM { this.cacheBehavior?.cacheSystemMessage && systemMessage ); + // /v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict + const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, this.apiBase, From 16755afc426c83cca57a210ede3df8aa0bf33c73 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 8 Jul 2025 17:27:04 -0700 Subject: [PATCH 2/4] docs: vertex express mode docs --- core/llm/llms/VertexAI.ts | 2 +- .../model-providers/top-level/vertexai.mdx | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index b7a5e7ecf..27351cf25 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -58,7 +58,7 @@ class VertexAI extends BaseLLM { if (apiKey) { if (this.vertexProvider !== "gemini") { throw new Error( - "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", + "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", ); } if (region || projectId) { diff --git a/docs/docs/customize/model-providers/top-level/vertexai.mdx b/docs/docs/customize/model-providers/top-level/vertexai.mdx index 2863acc31..383e404f1 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.mdx +++ b/docs/docs/customize/model-providers/top-level/vertexai.mdx @@ -114,3 +114,33 @@ We recommend configuring **text-embedding-004** as your embeddings model. Vertex AI currently does not offer any reranking models. [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. + +## Express mode + +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. + + + + ```yaml title="config.yaml" + models: + - name: Gemini 2.5 Flash - VertexAI + provider: vertexai + model: gemini-2.5-flash + apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }} + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemini 2.5 Flash - VertexAI", + "provider": "vertexai", + "model": "gemini-2.5-flash", + "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]", + } + ] + } + ``` + + From 5b17cb5d088641bf94301ee658ab8ec3dead9075 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 8 Jul 2025 23:06:41 -0700 Subject: [PATCH 3/4] vertexai json and keyFile support --- core/llm/llms/VertexAI.ts | 143 +++++++++++++++++++++++++++----------- 1 file changed, 101 insertions(+), 42 deletions(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 27351cf25..c428b9aa6 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,4 +1,4 @@ -import { GoogleAuth } from "google-auth-library"; +import { AuthClient, GoogleAuth, auth } from "google-auth-library"; import { streamResponse, streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; @@ -20,62 +20,33 @@ class VertexAI extends BaseLLM { region: "us-central1", }; - private clientPromise = new GoogleAuth({ - scopes: "https://www.googleapis.com/auth/cloud-platform", - }) - .getClient() - .catch((e) => { - console.warn(`Failed to load credentials for Vertex AI: ${e.message}`); - }); + private clientPromise: Promise; /* Vertex Supports 3 different URL formats - 1. 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 - 2. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent - 3. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent + 1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent + 2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent + 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 Authentication can be done using the following + 2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region 1. API Key (express mode), region and projectId will be ignored - 2. project id and region with Google Auth client In all cases we have defined apiBase to be up to everything including the location. - Express api base: https://aiplatform.googleapis.com/v1/ Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/ + Express api base: https://aiplatform.googleapis.com/v1/ TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet Note that VertexAI uses the term "service endpoint" and "model", like: {service-endpoint}/v1/{model}:streamGenerateContent So "model" includes the project, location, publisher, etc - Express mode has limited support + Express mode has limited support + and CRITICALLY is only available to NEW users who had NOT used cloud services before. + However it is pretty common as gemini becomes more popular. + Only Gemini models are supported for now https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models - supported methods: countTokens, generateContent, and streamGenerateContent - supported models: gemini for now (updating quickly) - - */ - private getDefaultApiBaseFrom(options: LLMOptions) { - const { region, projectId, apiKey } = options; - if (apiKey) { - if (this.vertexProvider !== "gemini") { - throw new Error( - "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", - ); - } - if (region || projectId) { - console.warn( - "Region and projectId are ignored when using apiKey. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview", - ); - } - return `https://aiplatform.googleapis.com/v1/`; - } - if (!region || !projectId) { - throw new Error( - "To authenticate VertexAI, either add your region and projectId, which will Google Cloud credientials, or add an apiKey (express mode)", - ); - } - return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; - } - + */ constructor(_options: LLMOptions) { if (_options.region !== "us-central1") { // Any region outside of us-central1 has a max batch size of 5. @@ -85,7 +56,7 @@ class VertexAI extends BaseLLM { ); } super(_options); - this.apiBase ??= this.getDefaultApiBaseFrom(_options); + this.vertexProvider = _options.model.includes("mistral") || _options.model.includes("codestral") || @@ -96,6 +67,93 @@ class VertexAI extends BaseLLM { : _options.model.includes("gemini") ? "gemini" : "unknown"; + + // Validate inputs + const { apiKey, region, projectId, env } = _options; + const keyFile = env?.keyFile; + const keyJson = env?.keyJson; + + // Acceptable setup: + // apiKey only + // region and projectId AND (keyFile OR keyJson OR nothing) + + if (apiKey) { + // Consider warning here instead of throwing error + if (region || projectId || keyFile || keyJson) { + throw new Error( + "Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson", + ); + // console.warn( + // "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", + // ); + } + if (this.vertexProvider !== "gemini") { + throw new Error( + "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", + ); + } + } else { + if (region && projectId) { + throw new Error( + "region and projectId are required for VertexAI (when not using express/apiKey mode)", + ); + } + if (keyFile && keyJson) { + throw new Error( + "VertexAI credentials can be configured with either keyFile or keyJson but not both", + ); + } + } + + if (!this.apiBase) { + if (apiKey) { + this.apiBase = `https://aiplatform.googleapis.com/v1/`; + } else { + this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; + } + } + + const scopes = "https://www.googleapis.com/auth/cloud-platform"; + if (keyJson) { + // Loading keys from manually set JSON + if (typeof keyJson !== "string") { + throw new Error("VertexAI: keyJson must be a JSON string"); + } + try { + const parsed = JSON.parse(keyJson); + this.clientPromise = Promise.resolve(auth.fromJSON(parsed)); + } catch (e) { + throw new Error("VertexAI: Failed to parse keyJson"); + } + } else if (keyFile) { + // Loading keys from manually set file path + if (typeof keyFile !== "string") { + throw new Error("VertexAI: keyFile must be a string"); + } + this.clientPromise = new GoogleAuth({ + scopes, + keyFile, + }) + .getClient() + .catch((e) => { + console.warn( + `Failed to load credentials for Vertex AI: ${e.message}`, + ); + }); + } else { + // Loading keys from local credentials or environment variable + this.clientPromise = new GoogleAuth({ + scopes, + }) + .getClient() + .catch((e) => { + console.warn( + `Failed to load credentials for Vertex AI: ${e.message}`, + ); + }); + } + + // Uses instances of other LLMs since underlying functionality is the same this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); } @@ -116,6 +174,7 @@ class VertexAI extends BaseLLM { } headers.Authorization = `Bearer ${result.token}`; } + return await super.fetch(url, { ...init, headers: { From 02678858ea90d839801f3f9c0906bf5400df7553 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 9 Jul 2025 00:48:39 -0700 Subject: [PATCH 4/4] feat: add keyFile and keyJson auth methods for vertexAI --- core/llm/llms/VertexAI.ts | 44 +++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index c428b9aa6..c3c2c9bf4 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,4 +1,4 @@ -import { AuthClient, GoogleAuth, auth } from "google-auth-library"; +import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library"; import { streamResponse, streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; @@ -14,6 +14,7 @@ class VertexAI extends BaseLLM { declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown"; declare anthropicInstance: Anthropic; declare geminiInstance: Gemini; + static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform"; static defaultOptions: Partial | undefined = { maxEmbeddingBatchSize: 250, @@ -68,12 +69,12 @@ class VertexAI extends BaseLLM { ? "gemini" : "unknown"; - // Validate inputs + // Set client authentication promise const { apiKey, region, projectId, env } = _options; const keyFile = env?.keyFile; const keyJson = env?.keyJson; - // Acceptable setup: + // Acceptable authentication methods: // apiKey only // region and projectId AND (keyFile OR keyJson OR nothing) @@ -93,7 +94,7 @@ class VertexAI extends BaseLLM { ); } } else { - if (region && projectId) { + if (!region && !projectId) { throw new Error( "region and projectId are required for VertexAI (when not using express/apiKey mode)", ); @@ -105,15 +106,6 @@ class VertexAI extends BaseLLM { } } - if (!this.apiBase) { - if (apiKey) { - this.apiBase = `https://aiplatform.googleapis.com/v1/`; - } else { - this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; - } - } - - const scopes = "https://www.googleapis.com/auth/cloud-platform"; if (keyJson) { // Loading keys from manually set JSON if (typeof keyJson !== "string") { @@ -121,7 +113,17 @@ class VertexAI extends BaseLLM { } try { const parsed = JSON.parse(keyJson); - this.clientPromise = Promise.resolve(auth.fromJSON(parsed)); + if (!parsed?.private_key) { + throw new Error("VertexAI: keyJson must contain a valid private key"); + } + parsed.private_key = parsed.private_key.replace(/\\n/g, "\n"); + const jsonClient = auth.fromJSON(parsed); + if (jsonClient instanceof JWT) { + jsonClient.scopes = [VertexAI.AUTH_SCOPES]; + } else { + throw new Error("VertexAI: keyJson must be a valid JWT"); + } + this.clientPromise = Promise.resolve(jsonClient); } catch (e) { throw new Error("VertexAI: Failed to parse keyJson"); } @@ -131,7 +133,7 @@ class VertexAI extends BaseLLM { throw new Error("VertexAI: keyFile must be a string"); } this.clientPromise = new GoogleAuth({ - scopes, + scopes: VertexAI.AUTH_SCOPES, keyFile, }) .getClient() @@ -143,7 +145,7 @@ class VertexAI extends BaseLLM { } else { // Loading keys from local credentials or environment variable this.clientPromise = new GoogleAuth({ - scopes, + scopes: VertexAI.AUTH_SCOPES, }) .getClient() .catch((e) => { @@ -153,6 +155,16 @@ class VertexAI extends BaseLLM { }); } + // Set api base + if (!this.apiBase) { + if (apiKey) { + // Express mode + this.apiBase = `https://aiplatform.googleapis.com/v1/`; + } else { + this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; + } + } + // Uses instances of other LLMs since underlying functionality is the same this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options);