Elffuss BraidHub

kikocis/continue public

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