| 1 | import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library"; |
| 2 | |
| 3 | import { streamResponse, streamSse } from "@continuedev/fetch"; |
| 4 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 5 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 6 | import { BaseLLM } from "../index.js"; |
| 7 | |
| 8 | import Anthropic from "./Anthropic.js"; |
| 9 | import Gemini from "./Gemini.js"; |
| 10 | |
| 11 | class VertexAI extends BaseLLM { |
| 12 | static providerName = "vertexai"; |
| 13 | declare apiBase: string; |
| 14 | declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown"; |
| 15 | declare anthropicInstance: Anthropic; |
| 16 | declare geminiInstance: Gemini; |
| 17 | static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform"; |
| 18 | |
| 19 | static defaultOptions: Partial<LLMOptions> | undefined = { |
| 20 | maxEmbeddingBatchSize: 250, |
| 21 | region: "us-central1", |
| 22 | }; |
| 23 | |
| 24 | private clientPromise: Promise<AuthClient | void>; |
| 25 | |
| 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 |
| 35 | |
| 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 | */ |
| 51 | constructor(_options: LLMOptions) { |
| 52 | if (_options.region !== "us-central1") { |
| 53 | // Any region outside of us-central1 has a max batch size of 5. |
| 54 | _options.maxEmbeddingBatchSize = Math.min( |
| 55 | _options.maxEmbeddingBatchSize ?? 5, |
| 56 | 5, |
| 57 | ); |
| 58 | } |
| 59 | super(_options); |
| 60 | |
| 61 | this.vertexProvider = |
| 62 | _options.model.includes("mistral") || |
| 63 | _options.model.includes("codestral") || |
| 64 | _options.model.includes("mixtral") |
| 65 | ? "mistral" |
| 66 | : _options.model.includes("claude") |
| 67 | ? "anthropic" |
| 68 | : _options.model.includes("gemini") |
| 69 | ? "gemini" |
| 70 | : "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 |
| 169 | this.anthropicInstance = new Anthropic(_options); |
| 170 | this.geminiInstance = new Gemini(_options); |
| 171 | } |
| 172 | |
| 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}`; |
| 188 | } |
| 189 | |
| 190 | return await super.fetch(url, { |
| 191 | ...init, |
| 192 | headers: { |
| 193 | ...init?.headers, |
| 194 | ...headers, |
| 195 | }, |
| 196 | }); |
| 197 | } |
| 198 | |
| 199 | // Anthropic functions |
| 200 | private _anthropicConvertArgs(options: CompletionOptions) { |
| 201 | const convertedArgs = this.anthropicInstance.convertArgs(options); |
| 202 | |
| 203 | // 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 |
| 208 | const { model, ...finalOptions } = convertedArgs; |
| 209 | return { |
| 210 | ...finalOptions, |
| 211 | anthropic_version: "vertex-2023-10-16", |
| 212 | }; |
| 213 | } |
| 214 | |
| 215 | protected async *StreamChatAnthropic( |
| 216 | messages: ChatMessage[], |
| 217 | options: CompletionOptions, |
| 218 | signal: AbortSignal, |
| 219 | ): AsyncGenerator<ChatMessage> { |
| 220 | const systemMessage = stripImages( |
| 221 | messages.filter((m) => m.role === "system")[0]?.content ?? "", |
| 222 | ); |
| 223 | const shouldCacheSystemMessage = !!( |
| 224 | this.cacheBehavior?.cacheSystemMessage && systemMessage |
| 225 | ); |
| 226 | const shouldCachePrompt = !!( |
| 227 | this.cacheBehavior?.cacheConversation ?? |
| 228 | this.completionOptions.promptCaching |
| 229 | ); |
| 230 | |
| 231 | // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict |
| 232 | |
| 233 | const apiURL = new URL( |
| 234 | `publishers/anthropic/models/${options.model}:streamRawPredict`, |
| 235 | this.apiBase, |
| 236 | ); |
| 237 | |
| 238 | const response = await this.fetch(apiURL, { |
| 239 | method: "POST", |
| 240 | headers: { |
| 241 | ...(shouldCacheSystemMessage || shouldCachePrompt |
| 242 | ? { "anthropic-beta": "prompt-caching-2024-07-31" } |
| 243 | : {}), |
| 244 | }, |
| 245 | body: JSON.stringify({ |
| 246 | ...this._anthropicConvertArgs(options), |
| 247 | messages: this.anthropicInstance.convertMessages( |
| 248 | messages, |
| 249 | shouldCachePrompt, |
| 250 | ), |
| 251 | system: shouldCacheSystemMessage |
| 252 | ? [ |
| 253 | { |
| 254 | type: "text", |
| 255 | text: systemMessage, |
| 256 | cache_control: { type: "ephemeral" }, |
| 257 | }, |
| 258 | ] |
| 259 | : systemMessage, |
| 260 | }), |
| 261 | signal, |
| 262 | }); |
| 263 | |
| 264 | yield* this.anthropicInstance.handleResponse(response, options.stream); |
| 265 | } |
| 266 | |
| 267 | // Gemini |
| 268 | private async *streamChatGemini( |
| 269 | messages: ChatMessage[], |
| 270 | options: CompletionOptions, |
| 271 | signal: AbortSignal, |
| 272 | ): AsyncGenerator<ChatMessage> { |
| 273 | const apiURL = new URL( |
| 274 | `publishers/google/models/${options.model}:streamGenerateContent`, |
| 275 | this.apiBase, |
| 276 | ); |
| 277 | |
| 278 | // For some reason gemini through vertex does not support ids in functionResponses yet |
| 279 | const body = this.geminiInstance.prepareBody( |
| 280 | messages, |
| 281 | options, |
| 282 | false, |
| 283 | false, |
| 284 | ); |
| 285 | const response = await this.fetch(apiURL, { |
| 286 | method: "POST", |
| 287 | body: JSON.stringify(body), |
| 288 | signal, |
| 289 | }); |
| 290 | yield* this.geminiInstance.processGeminiResponse(streamResponse(response)); |
| 291 | } |
| 292 | |
| 293 | private async *streamChatBison( |
| 294 | messages: ChatMessage[], |
| 295 | options: CompletionOptions, |
| 296 | signal: AbortSignal, |
| 297 | ): AsyncGenerator<ChatMessage> { |
| 298 | const instances = messages.map((message) => ({ prompt: message.content })); |
| 299 | |
| 300 | const apiURL = new URL( |
| 301 | `publishers/google/models/${options.model}:predict`, |
| 302 | this.apiBase, |
| 303 | ); |
| 304 | const body = { |
| 305 | instances, |
| 306 | parameters: { |
| 307 | temperature: options.temperature, |
| 308 | maxOutputTokens: options.maxTokens, |
| 309 | topP: options.topP, |
| 310 | topK: options.topK, |
| 311 | stopSequences: options.stop, |
| 312 | presencePenalty: options.presencePenalty, |
| 313 | frequencyPenalty: options.frequencyPenalty, |
| 314 | }, |
| 315 | }; |
| 316 | const response = await this.fetch(apiURL, { |
| 317 | method: "POST", |
| 318 | body: JSON.stringify(body), |
| 319 | signal, |
| 320 | }); |
| 321 | if (response.status === 499) { |
| 322 | return; // Aborted by user |
| 323 | } |
| 324 | const data = await response.json(); |
| 325 | yield { role: "assistant", content: data.predictions[0].content }; |
| 326 | } |
| 327 | |
| 328 | //Mistral |
| 329 | |
| 330 | protected async *StreamChatMistral( |
| 331 | messages: ChatMessage[], |
| 332 | options: CompletionOptions, |
| 333 | signal: AbortSignal, |
| 334 | ): AsyncGenerator<ChatMessage> { |
| 335 | const apiBase = this.apiBase!; |
| 336 | const apiURL = new URL( |
| 337 | `publishers/mistralai/models/${options.model}:streamRawPredict`, |
| 338 | apiBase, |
| 339 | ); |
| 340 | |
| 341 | const lastMessage = messages[messages.length - 1]; |
| 342 | if (lastMessage?.role === "assistant") { |
| 343 | (lastMessage as any).prefix = true; |
| 344 | } |
| 345 | |
| 346 | const body = { |
| 347 | model: options.model, |
| 348 | temperature: options.temperature, |
| 349 | top_p: options.topP, |
| 350 | max_tokens: options.maxTokens, |
| 351 | stream: options.stream ?? true, |
| 352 | stop: options.stop, |
| 353 | messages, |
| 354 | }; |
| 355 | |
| 356 | const response = await this.fetch(apiURL, { |
| 357 | method: "POST", |
| 358 | body: JSON.stringify(body), |
| 359 | signal, |
| 360 | }); |
| 361 | |
| 362 | for await (const chunk of streamSse(response)) { |
| 363 | if (chunk.choices?.[0]) { |
| 364 | // At the end vertexai will return a empty chunk. |
| 365 | yield chunk.choices[0].delta; |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | protected async *StreamFimMistral( |
| 371 | prefix: string, |
| 372 | suffix: string, |
| 373 | signal: AbortSignal, |
| 374 | options: CompletionOptions, |
| 375 | ): AsyncGenerator<string> { |
| 376 | const apiBase = this.apiBase!; |
| 377 | const apiURL = new URL( |
| 378 | `publishers/mistralai/models/${options.model}:streamRawPredict`, |
| 379 | apiBase, |
| 380 | ); |
| 381 | |
| 382 | const body = { |
| 383 | model: options.model, |
| 384 | max_tokens: options.maxTokens, |
| 385 | temperature: options.temperature, |
| 386 | top_p: options.topP, |
| 387 | stream: options.stream ?? true, |
| 388 | stop: options.stop, |
| 389 | prompt: prefix, |
| 390 | suffix, |
| 391 | }; |
| 392 | |
| 393 | const response = await this.fetch(apiURL, { |
| 394 | method: "POST", |
| 395 | body: JSON.stringify(body), |
| 396 | signal, |
| 397 | }); |
| 398 | |
| 399 | for await (const chunk of streamSse(response)) { |
| 400 | if (chunk.choices?.[0].delta) { |
| 401 | yield chunk.choices[0].delta.content; |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | //gecko |
| 407 | protected async *streamFimGecko( |
| 408 | prefix: string, |
| 409 | suffix: string, |
| 410 | signal: AbortSignal, |
| 411 | options: CompletionOptions, |
| 412 | ): AsyncGenerator<string> { |
| 413 | const endpoint = new URL( |
| 414 | "publishers/google/models/code-gecko:predict", |
| 415 | this.apiBase, |
| 416 | ); |
| 417 | const resp = await this.fetch(endpoint, { |
| 418 | method: "POST", |
| 419 | body: JSON.stringify({ |
| 420 | instances: [ |
| 421 | { |
| 422 | prefix: prefix, |
| 423 | suffix: suffix, |
| 424 | }, |
| 425 | ], |
| 426 | parameters: { |
| 427 | temperature: options.temperature, |
| 428 | maxOutputTokens: Math.min(options.maxTokens ?? 64, 64), |
| 429 | stopSequences: options.stop?.splice(0, 5), |
| 430 | frequencyPenalty: options.frequencyPenalty, |
| 431 | presencePenalty: options.frequencyPenalty, |
| 432 | }, |
| 433 | }), |
| 434 | signal, |
| 435 | }); |
| 436 | if (resp.status === 499) { |
| 437 | return; // Aborted by user |
| 438 | } |
| 439 | // Streaming is not supported by code-gecko |
| 440 | // TODO: convert to non-streaming fim method when one exist in continue. |
| 441 | yield (await resp.json()).predictions[0].content; |
| 442 | } |
| 443 | |
| 444 | // Manager functions |
| 445 | |
| 446 | protected async *_streamChat( |
| 447 | messages: ChatMessage[], |
| 448 | signal: AbortSignal, |
| 449 | options: CompletionOptions, |
| 450 | ): AsyncGenerator<ChatMessage> { |
| 451 | const isV1API = this.apiBase.includes("/v1/"); |
| 452 | |
| 453 | // Conditionally apply removeSystemMessage |
| 454 | const convertedMsgs = isV1API |
| 455 | ? this.geminiInstance.removeSystemMessage(messages) |
| 456 | : messages; |
| 457 | if (this.vertexProvider === "gemini") { |
| 458 | yield* this.streamChatGemini(convertedMsgs, options, signal); |
| 459 | } else if (this.vertexProvider === "mistral") { |
| 460 | yield* this.StreamChatMistral(messages, options, signal); |
| 461 | } else if (this.vertexProvider === "anthropic") { |
| 462 | yield* this.StreamChatAnthropic(messages, options, signal); |
| 463 | } else { |
| 464 | if (options.model.includes("bison")) { |
| 465 | yield* this.streamChatBison(convertedMsgs, options, signal); |
| 466 | } else { |
| 467 | throw new Error(`Unsupported model: ${options.model}`); |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | protected async *_streamComplete( |
| 473 | prompt: string, |
| 474 | signal: AbortSignal, |
| 475 | options: CompletionOptions, |
| 476 | ): AsyncGenerator<string> { |
| 477 | for await (const message of this._streamChat( |
| 478 | [{ content: prompt, role: "user" }], |
| 479 | signal, |
| 480 | options, |
| 481 | )) { |
| 482 | yield renderChatMessage(message); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | protected async *_streamFim( |
| 487 | prefix: string, |
| 488 | suffix: string, |
| 489 | signal: AbortSignal, |
| 490 | options: CompletionOptions, |
| 491 | ): AsyncGenerator<string> { |
| 492 | if (this.model === "code-gecko") { |
| 493 | yield* this.streamFimGecko(prefix, suffix, signal, options); |
| 494 | } else if (this.model.includes("codestral")) { |
| 495 | yield* this.StreamFimMistral(prefix, suffix, signal, options); |
| 496 | } else { |
| 497 | throw new Error(`Unsupported model: ${this.model}`); |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | supportsFim(): boolean { |
| 502 | return ( |
| 503 | this.model.includes("code-gecko") || this.model.includes("codestral") |
| 504 | ); |
| 505 | } |
| 506 | |
| 507 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 508 | const client = await this.clientPromise; |
| 509 | const result = await client?.getAccessToken(); |
| 510 | if (!result?.token) { |
| 511 | throw new Error( |
| 512 | "Could not get an access token. Set up your Google Application Default Credentials.", |
| 513 | ); |
| 514 | } |
| 515 | |
| 516 | const resp = await this.fetch( |
| 517 | new URL(`publishers/google/models/${this.model}:predict`, this.apiBase), |
| 518 | { |
| 519 | method: "POST", |
| 520 | body: JSON.stringify({ |
| 521 | instances: chunks.map((chunk) => ({ content: chunk })), |
| 522 | }), |
| 523 | headers: { |
| 524 | "Content-Type": "application/json", |
| 525 | Authorization: `Bearer ${result.token}`, |
| 526 | }, |
| 527 | }, |
| 528 | ); |
| 529 | |
| 530 | if (!resp.ok) { |
| 531 | throw new Error(await resp.text()); |
| 532 | } |
| 533 | |
| 534 | const data = (await resp.json()) as any; |
| 535 | return data.predictions.map( |
| 536 | (prediction: any) => prediction.embeddings.values, |
| 537 | ); |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | export default VertexAI; |