Elffuss BraidHub

kikocis/continue public

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