| 1 | import { GoogleAuth } 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 | |
| 18 | static defaultOptions: Partial<LLMOptions> | undefined = { |
| 19 | maxEmbeddingBatchSize: 250, |
| 20 | region: "us-central1", |
| 21 | }; |
| 22 | |
| 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 | }); |
| 30 | |
| 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 | } |
| 40 | |
| 41 | constructor(_options: LLMOptions) { |
| 42 | if (_options.region !== "us-central1") { |
| 43 | // Any region outside of us-central1 has a max batch size of 5. |
| 44 | _options.maxEmbeddingBatchSize = Math.min( |
| 45 | _options.maxEmbeddingBatchSize ?? 5, |
| 46 | 5, |
| 47 | ); |
| 48 | } |
| 49 | super(_options); |
| 50 | this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); |
| 51 | this.vertexProvider = |
| 52 | _options.model.includes("mistral") || |
| 53 | _options.model.includes("codestral") || |
| 54 | _options.model.includes("mixtral") |
| 55 | ? "mistral" |
| 56 | : _options.model.includes("claude") |
| 57 | ? "anthropic" |
| 58 | : _options.model.includes("gemini") |
| 59 | ? "gemini" |
| 60 | : "unknown"; |
| 61 | this.anthropicInstance = new Anthropic(_options); |
| 62 | this.geminiInstance = new Gemini(_options); |
| 63 | } |
| 64 | |
| 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 | ); |
| 72 | } |
| 73 | return await super.fetch(url, { |
| 74 | ...init, |
| 75 | headers: { |
| 76 | "Content-Type": "application/json", |
| 77 | Authorization: `Bearer ${result.token}`, |
| 78 | ...init?.headers, |
| 79 | }, |
| 80 | }); |
| 81 | } |
| 82 | |
| 83 | // Anthropic functions |
| 84 | private _anthropicConvertArgs(options: CompletionOptions) { |
| 85 | const convertedArgs = this.anthropicInstance.convertArgs(options); |
| 86 | |
| 87 | // Remove the `model` property and add `anthropic_version` |
| 88 | const { model, ...finalOptions } = convertedArgs; |
| 89 | return { |
| 90 | ...finalOptions, |
| 91 | anthropic_version: "vertex-2023-10-16", |
| 92 | }; |
| 93 | } |
| 94 | |
| 95 | protected async *StreamChatAnthropic( |
| 96 | messages: ChatMessage[], |
| 97 | options: CompletionOptions, |
| 98 | signal: AbortSignal, |
| 99 | ): AsyncGenerator<ChatMessage> { |
| 100 | const systemMessage = stripImages( |
| 101 | messages.filter((m) => m.role === "system")[0]?.content ?? "", |
| 102 | ); |
| 103 | const shouldCacheSystemMessage = !!( |
| 104 | this.cacheBehavior?.cacheSystemMessage && systemMessage |
| 105 | ); |
| 106 | |
| 107 | const apiURL = new URL( |
| 108 | `publishers/anthropic/models/${options.model}:streamRawPredict`, |
| 109 | this.apiBase, |
| 110 | ); |
| 111 | |
| 112 | const response = await this.fetch(apiURL, { |
| 113 | method: "POST", |
| 114 | headers: { |
| 115 | ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation |
| 116 | ? { "anthropic-beta": "prompt-caching-2024-07-31" } |
| 117 | : {}), |
| 118 | }, |
| 119 | body: JSON.stringify({ |
| 120 | ...this._anthropicConvertArgs(options), |
| 121 | messages: this.anthropicInstance.convertMessages(messages), |
| 122 | system: shouldCacheSystemMessage |
| 123 | ? [ |
| 124 | { |
| 125 | type: "text", |
| 126 | text: systemMessage, |
| 127 | cache_control: { type: "ephemeral" }, |
| 128 | }, |
| 129 | ] |
| 130 | : systemMessage, |
| 131 | }), |
| 132 | signal, |
| 133 | }); |
| 134 | |
| 135 | if (response.status === 499) { |
| 136 | return; // Aborted by user |
| 137 | } |
| 138 | |
| 139 | if (options.stream === false) { |
| 140 | const data = await response.json(); |
| 141 | yield { role: "assistant", content: data.content[0].text }; |
| 142 | return; |
| 143 | } |
| 144 | |
| 145 | for await (const value of streamSse(response)) { |
| 146 | if (value.type === "message_start") { |
| 147 | console.log(value); |
| 148 | } |
| 149 | if (value.delta?.text) { |
| 150 | yield { role: "assistant", content: value.delta.text }; |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // Gemini |
| 156 | private async *streamChatGemini( |
| 157 | messages: ChatMessage[], |
| 158 | options: CompletionOptions, |
| 159 | signal: AbortSignal, |
| 160 | ): AsyncGenerator<ChatMessage> { |
| 161 | const apiURL = new URL( |
| 162 | `publishers/google/models/${options.model}:streamGenerateContent`, |
| 163 | this.apiBase, |
| 164 | ); |
| 165 | |
| 166 | const body = this.geminiInstance.prepareBody(messages, options, false); |
| 167 | const response = await this.fetch(apiURL, { |
| 168 | method: "POST", |
| 169 | body: JSON.stringify(body), |
| 170 | signal, |
| 171 | }); |
| 172 | for await (const message of this.geminiInstance.processGeminiResponse( |
| 173 | streamResponse(response), |
| 174 | )) { |
| 175 | yield message; |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | private async *streamChatBison( |
| 180 | messages: ChatMessage[], |
| 181 | options: CompletionOptions, |
| 182 | signal: AbortSignal, |
| 183 | ): AsyncGenerator<ChatMessage> { |
| 184 | const instances = messages.map((message) => ({ prompt: message.content })); |
| 185 | |
| 186 | const apiURL = new URL( |
| 187 | `publishers/google/models/${options.model}:predict`, |
| 188 | this.apiBase, |
| 189 | ); |
| 190 | const body = { |
| 191 | instances, |
| 192 | parameters: { |
| 193 | temperature: options.temperature, |
| 194 | maxOutputTokens: options.maxTokens, |
| 195 | topP: options.topP, |
| 196 | topK: options.topK, |
| 197 | stopSequences: options.stop, |
| 198 | presencePenalty: options.presencePenalty, |
| 199 | frequencyPenalty: options.frequencyPenalty, |
| 200 | }, |
| 201 | }; |
| 202 | const response = await this.fetch(apiURL, { |
| 203 | method: "POST", |
| 204 | body: JSON.stringify(body), |
| 205 | signal, |
| 206 | }); |
| 207 | if (response.status === 499) { |
| 208 | return; // Aborted by user |
| 209 | } |
| 210 | const data = await response.json(); |
| 211 | yield { role: "assistant", content: data.predictions[0].content }; |
| 212 | } |
| 213 | |
| 214 | //Mistral |
| 215 | |
| 216 | protected async *StreamChatMistral( |
| 217 | messages: ChatMessage[], |
| 218 | options: CompletionOptions, |
| 219 | signal: AbortSignal, |
| 220 | ): AsyncGenerator<ChatMessage> { |
| 221 | const apiBase = this.apiBase!; |
| 222 | const apiURL = new URL( |
| 223 | `publishers/mistralai/models/${options.model}:streamRawPredict`, |
| 224 | apiBase, |
| 225 | ); |
| 226 | |
| 227 | const lastMessage = messages[messages.length - 1]; |
| 228 | if (lastMessage?.role === "assistant") { |
| 229 | (lastMessage as any).prefix = true; |
| 230 | } |
| 231 | |
| 232 | const body = { |
| 233 | model: options.model, |
| 234 | temperature: options.temperature, |
| 235 | top_p: options.topP, |
| 236 | max_tokens: options.maxTokens, |
| 237 | stream: options.stream ?? true, |
| 238 | stop: options.stop, |
| 239 | messages, |
| 240 | }; |
| 241 | |
| 242 | const response = await this.fetch(apiURL, { |
| 243 | method: "POST", |
| 244 | body: JSON.stringify(body), |
| 245 | signal, |
| 246 | }); |
| 247 | |
| 248 | for await (const chunk of streamSse(response)) { |
| 249 | if (chunk.choices?.[0]) { |
| 250 | // At the end vertexai will return a empty chunk. |
| 251 | yield chunk.choices[0].delta; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | protected async *StreamFimMistral( |
| 257 | prefix: string, |
| 258 | suffix: string, |
| 259 | signal: AbortSignal, |
| 260 | options: CompletionOptions, |
| 261 | ): AsyncGenerator<string> { |
| 262 | const apiBase = this.apiBase!; |
| 263 | const apiURL = new URL( |
| 264 | `publishers/mistralai/models/${options.model}:streamRawPredict`, |
| 265 | apiBase, |
| 266 | ); |
| 267 | |
| 268 | const body = { |
| 269 | model: options.model, |
| 270 | max_tokens: options.maxTokens, |
| 271 | temperature: options.temperature, |
| 272 | top_p: options.topP, |
| 273 | stream: options.stream ?? true, |
| 274 | stop: options.stop, |
| 275 | prompt: prefix, |
| 276 | suffix, |
| 277 | }; |
| 278 | |
| 279 | const response = await this.fetch(apiURL, { |
| 280 | method: "POST", |
| 281 | body: JSON.stringify(body), |
| 282 | signal, |
| 283 | }); |
| 284 | |
| 285 | for await (const chunk of streamSse(response)) { |
| 286 | if (chunk.choices?.[0].delta) { |
| 287 | yield chunk.choices[0].delta.content; |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | //gecko |
| 293 | protected async *streamFimGecko( |
| 294 | prefix: string, |
| 295 | suffix: string, |
| 296 | signal: AbortSignal, |
| 297 | options: CompletionOptions, |
| 298 | ): AsyncGenerator<string> { |
| 299 | const endpoint = new URL( |
| 300 | "publishers/google/models/code-gecko:predict", |
| 301 | this.apiBase, |
| 302 | ); |
| 303 | const resp = await this.fetch(endpoint, { |
| 304 | method: "POST", |
| 305 | body: JSON.stringify({ |
| 306 | instances: [ |
| 307 | { |
| 308 | prefix: prefix, |
| 309 | suffix: suffix, |
| 310 | }, |
| 311 | ], |
| 312 | parameters: { |
| 313 | temperature: options.temperature, |
| 314 | maxOutputTokens: Math.min(options.maxTokens ?? 64, 64), |
| 315 | stopSequences: options.stop?.splice(0, 5), |
| 316 | frequencyPenalty: options.frequencyPenalty, |
| 317 | presencePenalty: options.frequencyPenalty, |
| 318 | }, |
| 319 | }), |
| 320 | signal, |
| 321 | }); |
| 322 | if (resp.status === 499) { |
| 323 | return; // Aborted by user |
| 324 | } |
| 325 | // Streaming is not supported by code-gecko |
| 326 | // TODO: convert to non-streaming fim method when one exist in continue. |
| 327 | yield (await resp.json()).predictions[0].content; |
| 328 | } |
| 329 | |
| 330 | // Manager functions |
| 331 | |
| 332 | protected async *_streamChat( |
| 333 | messages: ChatMessage[], |
| 334 | signal: AbortSignal, |
| 335 | options: CompletionOptions, |
| 336 | ): AsyncGenerator<ChatMessage> { |
| 337 | const isV1API = this.apiBase.includes("/v1/"); |
| 338 | |
| 339 | // Conditionally apply removeSystemMessage |
| 340 | const convertedMsgs = isV1API |
| 341 | ? this.geminiInstance.removeSystemMessage(messages) |
| 342 | : messages; |
| 343 | if (this.vertexProvider === "gemini") { |
| 344 | yield* this.streamChatGemini(convertedMsgs, options, signal); |
| 345 | } else if (this.vertexProvider === "mistral") { |
| 346 | yield* this.StreamChatMistral(messages, options, signal); |
| 347 | } else if (this.vertexProvider === "anthropic") { |
| 348 | yield* this.StreamChatAnthropic(messages, options, signal); |
| 349 | } else { |
| 350 | if (options.model.includes("bison")) { |
| 351 | yield* this.streamChatBison(convertedMsgs, options, signal); |
| 352 | } else { |
| 353 | throw new Error(`Unsupported model: ${options.model}`); |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | protected async *_streamComplete( |
| 359 | prompt: string, |
| 360 | signal: AbortSignal, |
| 361 | options: CompletionOptions, |
| 362 | ): AsyncGenerator<string> { |
| 363 | for await (const message of this._streamChat( |
| 364 | [{ content: prompt, role: "user" }], |
| 365 | signal, |
| 366 | options, |
| 367 | )) { |
| 368 | yield renderChatMessage(message); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | protected async *_streamFim( |
| 373 | prefix: string, |
| 374 | suffix: string, |
| 375 | signal: AbortSignal, |
| 376 | options: CompletionOptions, |
| 377 | ): AsyncGenerator<string> { |
| 378 | if (this.model === "code-gecko") { |
| 379 | yield* this.streamFimGecko(prefix, suffix, signal, options); |
| 380 | } else if (this.model.includes("codestral")) { |
| 381 | yield* this.StreamFimMistral(prefix, suffix, signal, options); |
| 382 | } else { |
| 383 | throw new Error(`Unsupported model: ${this.model}`); |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | supportsFim(): boolean { |
| 388 | return ( |
| 389 | this.model.includes("code-gecko") || this.model.includes("codestral") |
| 390 | ); |
| 391 | } |
| 392 | |
| 393 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 394 | const client = await this.clientPromise; |
| 395 | const result = await client?.getAccessToken(); |
| 396 | if (!result?.token) { |
| 397 | throw new Error( |
| 398 | "Could not get an access token. Set up your Google Application Default Credentials.", |
| 399 | ); |
| 400 | } |
| 401 | |
| 402 | const resp = await this.fetch( |
| 403 | new URL(`publishers/google/models/${this.model}:predict`, this.apiBase), |
| 404 | { |
| 405 | method: "POST", |
| 406 | body: JSON.stringify({ |
| 407 | instances: chunks.map((chunk) => ({ content: chunk })), |
| 408 | }), |
| 409 | headers: { |
| 410 | "Content-Type": "application/json", |
| 411 | Authorization: `Bearer ${result.token}`, |
| 412 | }, |
| 413 | }, |
| 414 | ); |
| 415 | |
| 416 | if (!resp.ok) { |
| 417 | throw new Error(await resp.text()); |
| 418 | } |
| 419 | |
| 420 | const data = (await resp.json()) as any; |
| 421 | return data.predictions.map( |
| 422 | (prediction: any) => prediction.embeddings.values, |
| 423 | ); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | export default VertexAI; |