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