Elffuss BraidHub

kikocis/continue public

main · 15.8 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParams,
7 ChatCompletionCreateParamsNonStreaming,
8 ChatCompletionCreateParamsStreaming,
9 Completion,
10 CompletionCreateParamsNonStreaming,
11 CompletionCreateParamsStreaming,
12 CreateEmbeddingResponse,
13 EmbeddingCreateParams,
14 Model,
15} from "openai/resources/index";
16import { VertexAIConfig } from "../types.js";
17import { chatChunk, chatCompletion, customFetch, embedding } from "../util.js";
18import { AnthropicApi } from "./Anthropic.js";
19import {
20 BaseLlmApi,
21 CreateRerankResponse,
22 FimCreateParamsStreaming,
23 RerankCreateParams,
24} from "./base.js";
25import { GeminiApi } from "./Gemini.js";
26import { OpenAIApi } from "./OpenAI.js";
27
28export class VertexAIApi implements BaseLlmApi {
29 anthropicInstance: AnthropicApi;
30 geminiInstance: GeminiApi;
31 mistralInstance: OpenAIApi;
32 private clientPromise?: Promise<AuthClient | void>;
33 static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
34
35 constructor(protected config: VertexAIConfig) {
36 this.setupAuthentication();
37
38 // These sub-instances are only used to convert and handle responses,
39 // So do not need apiKey, etc
40 this.anthropicInstance = new AnthropicApi({
41 provider: "anthropic",
42 apiKey: "dud",
43 });
44 this.geminiInstance = new GeminiApi({
45 provider: "gemini",
46 apiKey: "dud",
47 });
48 this.mistralInstance = new OpenAIApi({
49 provider: "mistral",
50 apiKey: "dud",
51 });
52 }
53
54 private setupAuthentication(): void {
55 const { apiKey, env } = this.config;
56 const { region, projectId, keyFile, keyJson } = env || {};
57
58 // Validate authentication configuration
59 if (apiKey) {
60 // Express mode validation
61 if (region || projectId || keyFile || keyJson) {
62 throw new Error(
63 "VertexAI in express mode (apiKey only) cannot be configured with region, projectId, keyFile, or keyJson",
64 );
65 }
66 } else {
67 // Standard mode validation
68 if (!region || !projectId) {
69 throw new Error(
70 "region and projectId are required for VertexAI (when not using express/apiKey mode)",
71 );
72 }
73 if (keyFile && keyJson) {
74 throw new Error(
75 "VertexAI credentials can be configured with either keyFile or keyJson but not both",
76 );
77 }
78 }
79
80 // Set up authentication client
81 if (keyJson) {
82 try {
83 const parsed = JSON.parse(keyJson);
84 if (!parsed?.private_key) {
85 throw new Error("VertexAI: keyJson must contain a valid private key");
86 }
87 parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
88 const jsonClient = auth.fromJSON(parsed);
89 if (jsonClient instanceof JWT) {
90 jsonClient.scopes = [VertexAIApi.AUTH_SCOPES];
91 } else {
92 throw new Error("VertexAI: keyJson must be a valid JWT");
93 }
94 this.clientPromise = Promise.resolve(jsonClient);
95 } catch (e) {
96 throw new Error("VertexAI: Failed to parse keyJson");
97 }
98 } else if (keyFile) {
99 if (typeof keyFile !== "string") {
100 throw new Error("VertexAI: keyFile must be a string");
101 }
102 this.clientPromise = new GoogleAuth({
103 scopes: VertexAIApi.AUTH_SCOPES,
104 keyFile,
105 })
106 .getClient()
107 .catch((e: Error) => {
108 console.warn(
109 `Failed to load credentials for Vertex AI: ${e.message}`,
110 );
111 });
112 } else if (!apiKey) {
113 // Application Default Credentials
114 this.clientPromise = new GoogleAuth({
115 scopes: VertexAIApi.AUTH_SCOPES,
116 })
117 .getClient()
118 .catch((e: Error) => {
119 console.warn(
120 `Failed to load credentials for Vertex AI: ${e.message}`,
121 );
122 });
123 }
124 }
125
126 private getApiBase(): string {
127 const { apiKey, env } = this.config;
128
129 if (this.config.apiBase) {
130 return this.config.apiBase;
131 }
132
133 if (apiKey) {
134 // Express mode
135 return "https://aiplatform.googleapis.com/v1/";
136 } else {
137 // Standard mode
138 const { region, projectId } = env!;
139 return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
140 }
141 }
142
143 private determineVertexProvider(
144 model: string,
145 ): "mistral" | "anthropic" | "gemini" | "unknown" {
146 if (
147 model.includes("mistral") ||
148 model.includes("codestral") ||
149 model.includes("mixtral")
150 ) {
151 return "mistral";
152 } else if (model.includes("claude")) {
153 return "anthropic";
154 } else if (model.includes("gemini")) {
155 return "gemini";
156 }
157 return "unknown";
158 }
159
160 private async getAuthHeaders(): Promise<Record<string, string>> {
161 const headers: Record<string, string> = {
162 "Content-Type": "application/json",
163 // Accept: "application/json"
164 };
165
166 // TODO - support anthropic prompt caching with "anthropic-beta" header
167
168 if (this.config.apiKey) {
169 // Express mode - no Authorization header needed, API key is in URL
170 return headers;
171 } else {
172 // Standard mode - use OAuth token
173 const client = await this.clientPromise;
174 const result = await client?.getAccessToken();
175 if (!result?.token) {
176 throw new Error(
177 "Could not get an access token. Set up your Google Application Default Credentials.",
178 );
179 }
180 headers.Authorization = `Bearer ${result.token}`;
181 return headers;
182 }
183 }
184
185 private buildUrl(endpoint: string, model?: string): URL {
186 const apiBase = this.getApiBase();
187 const url = new URL(endpoint, apiBase);
188
189 if (this.config.apiKey) {
190 url.searchParams.set("key", this.config.apiKey);
191 }
192
193 return url;
194 }
195
196 private convertAnthropicBody(oaiBody: ChatCompletionCreateParams): object {
197 const body = this.anthropicInstance._convertToCleanAnthropicBody(oaiBody);
198 const { model, ...exceptModel } = body;
199 return {
200 ...exceptModel,
201 anthropic_version: "vertex-2023-10-16",
202 };
203 }
204
205 private convertGeminiBody(
206 oaiBody: ChatCompletionCreateParams,
207 url: URL,
208 ): object {
209 return this.geminiInstance._convertBody(
210 oaiBody,
211 url.toString(),
212 false,
213 false,
214 );
215 }
216
217 async chatCompletionNonStream(
218 body: ChatCompletionCreateParamsNonStreaming,
219 signal: AbortSignal,
220 ): Promise<ChatCompletion> {
221 const vertexProvider = this.determineVertexProvider(body.model);
222
223 if (this.config.apiKey && vertexProvider !== "gemini") {
224 throw new Error(
225 "VertexAI: only gemini models are supported in express (apiKey) mode",
226 );
227 }
228
229 const headers = await this.getAuthHeaders();
230 let url: URL;
231 let requestBody: any;
232
233 switch (vertexProvider) {
234 case "anthropic":
235 url = this.buildUrl(
236 `publishers/anthropic/models/${body.model}:rawPredict`,
237 );
238 requestBody = this.convertAnthropicBody(body);
239 break;
240 case "gemini":
241 url = this.buildUrl(
242 `publishers/google/models/${body.model}:generateContent`,
243 );
244 requestBody = this.convertGeminiBody(body, url);
245 break;
246 case "mistral":
247 url = this.buildUrl(
248 `publishers/mistralai/models/${body.model}:rawPredict`,
249 );
250 requestBody = body;
251 break;
252 default:
253 throw new Error(`Unsupported model: ${body.model}`);
254 }
255
256 const response = await customFetch(this.config.requestOptions)(
257 url.toString(),
258 {
259 method: "POST",
260 headers,
261 body: JSON.stringify(requestBody),
262 signal,
263 },
264 );
265
266 const data = await response.json();
267
268 if (!response.ok) {
269 throw new Error(
270 `VertexAI API error: ${response.status} ${response.statusText}\n${JSON.stringify(data)}`,
271 );
272 }
273
274 // Convert response to OpenAI format
275 switch (vertexProvider) {
276 case "anthropic":
277 return chatCompletion({
278 content: data.content?.[0]?.text || "",
279 model: body.model,
280 });
281 case "gemini":
282 return chatCompletion({
283 content: data.candidates?.[0]?.content?.parts?.[0]?.text || "",
284 model: body.model,
285 });
286 case "mistral":
287 return chatCompletion({
288 content: data.choices?.[0]?.message?.content || "",
289 model: body.model,
290 });
291 default:
292 throw new Error(`Unsupported provider: ${vertexProvider}`);
293 }
294 }
295
296 async *chatCompletionStream(
297 body: ChatCompletionCreateParamsStreaming,
298 signal: AbortSignal,
299 ): AsyncGenerator<ChatCompletionChunk> {
300 const vertexProvider = this.determineVertexProvider(body.model);
301
302 if (this.config.apiKey && vertexProvider !== "gemini") {
303 throw new Error(
304 "VertexAI: only gemini models are supported in express (apiKey) mode",
305 );
306 }
307
308 const headers = await this.getAuthHeaders();
309 let url: URL;
310 let requestBody: any;
311
312 switch (vertexProvider) {
313 case "anthropic":
314 url = this.buildUrl(
315 `publishers/anthropic/models/${body.model}:streamRawPredict`,
316 );
317 requestBody = this.convertAnthropicBody(body);
318 break;
319 case "gemini":
320 url = this.buildUrl(
321 `publishers/google/models/${body.model}:streamGenerateContent`,
322 );
323 requestBody = this.convertGeminiBody(body, url);
324 break;
325 case "mistral":
326 url = this.buildUrl(
327 `publishers/mistralai/models/${body.model}:streamRawPredict`,
328 );
329 requestBody = body;
330 break;
331 default:
332 throw new Error(`Unsupported model: ${body.model}`);
333 }
334
335 switch (vertexProvider) {
336 case "mistral":
337 const mistralResponse =
338 await this.mistralInstance.openai.chat.completions.create(
339 this.mistralInstance.modifyChatBody(body),
340 {
341 signal,
342 headers,
343 },
344 );
345 for await (const result of mistralResponse) {
346 yield result;
347 }
348 break;
349 case "anthropic":
350 case "gemini":
351 const response = await customFetch(this.config.requestOptions)(
352 url.toString(),
353 {
354 method: "POST",
355 headers,
356 body: JSON.stringify(requestBody),
357 signal,
358 },
359 );
360
361 if (!response.ok) {
362 const data = await response.json();
363 throw new Error(
364 `VertexAI API error: ${response.status} ${response.statusText}\n${JSON.stringify(data)}`,
365 );
366 }
367
368 if (response.status === 499) {
369 return; // Aborted by user
370 }
371 if (vertexProvider === "gemini") {
372 yield* this.geminiInstance.handleStreamResponse(response, body.model);
373 } else {
374 yield* this.anthropicInstance.handleStreamResponse(
375 response,
376 body.model,
377 );
378 }
379 break;
380 }
381 }
382
383 async completionNonStream(
384 body: CompletionCreateParamsNonStreaming,
385 signal: AbortSignal,
386 ): Promise<Completion> {
387 // Convert completion to chat completion and back
388 const promptText =
389 typeof body.prompt === "string"
390 ? body.prompt
391 : Array.isArray(body.prompt)
392 ? body.prompt.join("")
393 : "";
394
395 const chatBody: ChatCompletionCreateParamsNonStreaming = {
396 model: body.model,
397 messages: [{ role: "user", content: promptText }],
398 max_tokens: body.max_tokens,
399 temperature: body.temperature,
400 top_p: body.top_p,
401 stop: body.stop,
402 stream: false,
403 };
404
405 const chatResponse = await this.chatCompletionNonStream(chatBody, signal);
406
407 return {
408 id: chatResponse.id,
409 object: "text_completion",
410 created: chatResponse.created,
411 model: chatResponse.model,
412 choices: [
413 {
414 text: chatResponse.choices[0]?.message?.content || "",
415 index: 0,
416 logprobs: null,
417 finish_reason: chatResponse.choices[0]?.finish_reason || null,
418 },
419 ],
420 usage: chatResponse.usage,
421 } as Completion;
422 }
423
424 async *completionStream(
425 body: CompletionCreateParamsStreaming,
426 signal: AbortSignal,
427 ): AsyncGenerator<Completion> {
428 // Convert completion to chat completion and back
429 const promptText =
430 typeof body.prompt === "string"
431 ? body.prompt
432 : Array.isArray(body.prompt)
433 ? body.prompt.join("")
434 : "";
435
436 const chatBody: ChatCompletionCreateParamsStreaming = {
437 model: body.model,
438 messages: [{ role: "user", content: promptText }],
439 max_tokens: body.max_tokens,
440 temperature: body.temperature,
441 top_p: body.top_p,
442 stop: body.stop,
443 stream: true,
444 };
445
446 for await (const chatChunk of this.chatCompletionStream(chatBody, signal)) {
447 yield {
448 id: chatChunk.id,
449 object: "text_completion",
450 created: chatChunk.created,
451 model: chatChunk.model,
452 choices: [
453 {
454 text: chatChunk.choices[0]?.delta?.content || "",
455 index: 0,
456 logprobs: null,
457 finish_reason: chatChunk.choices[0]?.finish_reason || null,
458 },
459 ],
460 } as Completion;
461 }
462 }
463
464 async *fimStream(
465 body: FimCreateParamsStreaming,
466 signal: AbortSignal,
467 ): AsyncGenerator<ChatCompletionChunk> {
468 // Only Codestral (Mistral) supports FIM in VertexAI
469 if (!body.model.includes("codestral")) {
470 throw new Error(
471 `FIM is only supported for Codestral models, got: ${body.model}`,
472 );
473 }
474
475 const headers = await this.getAuthHeaders();
476 const url = this.buildUrl(
477 `publishers/mistralai/models/${body.model}:streamRawPredict`,
478 );
479
480 const requestBody = {
481 model: body.model,
482 max_tokens: body.max_tokens,
483 temperature: body.temperature,
484 top_p: body.top_p,
485 stream: body.stream ?? true,
486 stop: body.stop,
487 prompt: body.prompt,
488 suffix: body.suffix,
489 };
490
491 const response = await customFetch(this.config.requestOptions)(
492 url.toString(),
493 {
494 method: "POST",
495 headers,
496 body: JSON.stringify(requestBody),
497 signal,
498 },
499 );
500
501 if (!response.ok) {
502 throw new Error(
503 `VertexAI API error: ${response.status} ${response.statusText}`,
504 );
505 }
506
507 for await (const chunk of streamSse(response)) {
508 if (chunk.choices?.[0]?.delta?.content) {
509 yield chatChunk({
510 content: chunk.choices[0].delta.content,
511 model: body.model,
512 });
513 }
514 }
515 }
516
517 async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
518 const headers = await this.getAuthHeaders();
519 const url = this.buildUrl(`publishers/google/models/${body.model}:predict`);
520
521 // Convert input to text strings
522 const textInputs = Array.isArray(body.input)
523 ? body.input.map((item) =>
524 typeof item === "string" ? item : JSON.stringify(item),
525 )
526 : [
527 typeof body.input === "string"
528 ? body.input
529 : JSON.stringify(body.input),
530 ];
531
532 const requestBody = {
533 instances: textInputs.map((text) => ({ content: text })),
534 };
535
536 const response = await customFetch(this.config.requestOptions)(
537 url.toString(),
538 {
539 method: "POST",
540 headers,
541 body: JSON.stringify(requestBody),
542 },
543 );
544
545 if (!response.ok) {
546 throw new Error(
547 `VertexAI API error: ${response.status} ${response.statusText}`,
548 );
549 }
550
551 const data = await response.json();
552 const embeddings = data.predictions.map(
553 (prediction: any) => prediction.embeddings.values,
554 );
555
556 return embedding({
557 data: embeddings,
558 model: body.model,
559 });
560 }
561
562 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
563 throw new Error("Reranking is not supported by VertexAI");
564 }
565
566 async list(): Promise<Model[]> {
567 throw new Error("VertexAI provider does not support model listing.");
568 }
569}