Elffuss BraidHub

kikocis/continue public

feat: vertex ai openai adapter (#6736)

* feat: vertex ai openai adapter

* fix: vertex ai - missing mistral key

* feat: support tools for vertexAI gemini and anthropic

* feat: vertex openai adapter working for gemini

* fix: show errors in vertex ai

* fix: filter out model from vertexai anthropic body

* feat: vertexai toolSupport update

* chore: remove force openai adapter usage for vertex

* fix: prettier
Changesetd5669e48ee7b36139d68056ceae111e5479fb5f700f58c457649a30a33da1a19
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-25 05:38 +07:00
CommitterGitHub <noreply@github.com> · 2025-07-24 15:38 -07:00
Parents013fe1fc87fc

Browse the files at this changeset

12 files changed

modified core/llm/llms/Anthropic.ts +53 −46
@@ -172,52 +172,10 @@
172172 }
173173 }
174174
175- protected async *_streamChat(
176- messages: ChatMessage[],
177- signal: AbortSignal,
178- options: CompletionOptions,
175+ async *handleResponse(
176+ response: any,
177+ stream: boolean | undefined,
179178 ): AsyncGenerator<ChatMessage> {
180- if (!this.apiKey || this.apiKey === "") {
181- throw new Error(
182- "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
183- );
184- }
185-
186- const systemMessage = stripImages(
187- messages.filter((m) => m.role === "system")[0]?.content ?? "",
188- );
189- const shouldCacheSystemMessage = !!(
190- this.cacheBehavior?.cacheSystemMessage && systemMessage
191- );
192-
193- const msgs = this.convertMessages(messages);
194- const response = await this.fetch(new URL("messages", this.apiBase), {
195- method: "POST",
196- headers: {
197- "Content-Type": "application/json",
198- Accept: "application/json",
199- "anthropic-version": "2023-06-01",
200- "x-api-key": this.apiKey as string,
201- ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
202- ? { "anthropic-beta": "prompt-caching-2024-07-31" }
203- : {}),
204- },
205- body: JSON.stringify({
206- ...this.convertArgs(options),
207- messages: msgs,
208- system: shouldCacheSystemMessage
209- ? [
210- {
211- type: "text",
212- text: systemMessage,
213- cache_control: { type: "ephemeral" },
214- },
215- ]
216- : systemMessage,
217- }),
218- signal,
219- });
220-
221179 if (response.status === 499) {
222180 return; // Aborted by user
223181 }
@@ -237,7 +195,7 @@
237195 );
238196 }
239197
240- if (options.stream === false) {
198+ if (stream === false) {
241199 const data = await response.json();
242200 const cost = data.usage
243201 ? {
@@ -348,6 +306,55 @@
348306 usage,
349307 };
350308 }
309+
310+ protected async *_streamChat(
311+ messages: ChatMessage[],
312+ signal: AbortSignal,
313+ options: CompletionOptions,
314+ ): AsyncGenerator<ChatMessage> {
315+ if (!this.apiKey || this.apiKey === "") {
316+ throw new Error(
317+ "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
318+ );
319+ }
320+
321+ const systemMessage = stripImages(
322+ messages.filter((m) => m.role === "system")[0]?.content ?? "",
323+ );
324+ const shouldCacheSystemMessage = !!(
325+ this.cacheBehavior?.cacheSystemMessage && systemMessage
326+ );
327+
328+ const msgs = this.convertMessages(messages);
329+ const response = await this.fetch(new URL("messages", this.apiBase), {
330+ method: "POST",
331+ headers: {
332+ "Content-Type": "application/json",
333+ Accept: "application/json",
334+ "anthropic-version": "2023-06-01",
335+ "x-api-key": this.apiKey as string,
336+ ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
337+ ? { "anthropic-beta": "prompt-caching-2024-07-31" }
338+ : {}),
339+ },
340+ body: JSON.stringify({
341+ ...this.convertArgs(options),
342+ messages: msgs,
343+ system: shouldCacheSystemMessage
344+ ? [
345+ {
346+ type: "text",
347+ text: systemMessage,
348+ cache_control: { type: "ephemeral" },
349+ },
350+ ]
351+ : systemMessage,
352+ }),
353+ signal,
354+ });
355+
356+ yield* this.handleResponse(response, options.stream);
357+ }
351358 }
352359
353360 export default Anthropic;
modified core/llm/llms/Gemini.ts +3 −2
@@ -200,6 +200,7 @@
200200 messages: ChatMessage[],
201201 options: CompletionOptions,
202202 isV1API: boolean,
203+ includeToolIds: boolean,
203204 ): GeminiChatRequestBody {
204205 const toolCallIdToNameMap = new Map<string, string>();
205206 messages.forEach((msg) => {
@@ -231,7 +232,7 @@
231232 parts: [
232233 {
233234 functionResponse: {
234- id: msg.toolCallId,
235+ id: includeToolIds ? msg.toolCallId : undefined,
235236 name: functionName || "unknown",
236237 response: {
237238 output: msg.content, // "output" key is opinionated - not all functions will output objects
@@ -406,7 +407,7 @@
406407 const isV1API = !!this.apiBase?.includes("/v1/");
407408
408409 // Convert chat messages to contents
409- const body = this.prepareBody(messages, options, isV1API);
410+ const body = this.prepareBody(messages, options, isV1API, true);
410411
411412 const response = await this.fetch(apiURL, {
412413 method: "POST",
modified core/llm/llms/Mistral.ts +1 −1
@@ -67,7 +67,7 @@
6767 return Mistral.modelConversion[model] ?? model;
6868 }
6969
70- protected _convertArgs(options: any, messages: ChatMessage[]) {
70+ _convertArgs(options: any, messages: ChatMessage[]) {
7171 const finalOptions = super._convertArgs(options, messages);
7272
7373 const lastMessage = finalOptions.messages[finalOptions.messages.length - 1];
modified core/llm/llms/VertexAI.ts +9 −24
@@ -254,24 +254,7 @@
254254 signal,
255255 });
256256
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- }
257+ yield* this.anthropicInstance.handleResponse(response, options.stream);
275258 }
276259
277260 // Gemini
@@ -285,17 +268,19 @@
285268 this.apiBase,
286269 );
287270
288- const body = this.geminiInstance.prepareBody(messages, options, false);
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+ );
289278 const response = await this.fetch(apiURL, {
290279 method: "POST",
291280 body: JSON.stringify(body),
292281 signal,
293282 });
294- for await (const message of this.geminiInstance.processGeminiResponse(
295- streamResponse(response),
296- )) {
297- yield message;
298- }
283+ yield* this.geminiInstance.processGeminiResponse(streamResponse(response));
299284 }
300285
301286 private async *streamChatBison(
modified core/llm/toolSupport.ts +5 −4
@@ -83,11 +83,12 @@
8383 return model.toLowerCase().includes("gemini");
8484 },
8585 vertexai: (model) => {
86+ const lowerCaseModel = model.toLowerCase();
8687 // All gemini models except flash 2.0 lite support function calling
87- return (
88- model.toLowerCase().includes("gemini") &&
89- !model.toLowerCase().includes("lite")
90- );
88+ if (lowerCaseModel.includes("lite")) {
89+ return false;
90+ }
91+ return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val));
9192 },
9293 bedrock: (model) => {
9394 if (
modified packages/openai-adapters/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/openai-adapters/package.json +1 −0
@@ -18,6 +18,7 @@
1818 "@continuedev/config-yaml": "^1.0.51",
1919 "@continuedev/fetch": "^1.0.15",
2020 "dotenv": "^16.5.0",
21+ "google-auth-library": "^10.1.0",
2122 "json-schema": "^0.4.0",
2223 "node-fetch": "^3.3.2",
2324 "openai": "^4.104.0",
modified packages/openai-adapters/src/apis/Anthropic.ts +29 −24
@@ -55,7 +55,7 @@
5555 return cachingStrategy(cleanBody);
5656 }
5757
58- private _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
58+ public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
5959 let stop = undefined;
6060 if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
6161 stop = oaiBody.stop.filter((x) => x.trim() !== "");
@@ -219,27 +219,9 @@
219219 ],
220220 };
221221 }
222- async *chatCompletionStream(
223- body: ChatCompletionCreateParamsStreaming,
224- signal: AbortSignal,
225- ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
226- body.messages;
227- const response = await customFetch(this.config.requestOptions)(
228- new URL("messages", this.apiBase),
229- {
230- method: "POST",
231- headers: {
232- "Content-Type": "application/json",
233- Accept: "application/json",
234- "anthropic-version": "2023-06-01",
235- "anthropic-beta": "prompt-caching-2024-07-31",
236- "x-api-key": this.config.apiKey,
237- },
238- body: JSON.stringify(this._convertBody(body)),
239- signal,
240- },
241- );
242222
223+ // This is split off so e.g. VertexAI can use it
224+ async *handleStreamResponse(response: any, model: string) {
243225 let lastToolUseId: string | undefined;
244226 let lastToolUseName: string | undefined;
245227
@@ -272,7 +254,7 @@
272254 case "text_delta":
273255 yield chatChunk({
274256 content: value.delta.text,
275- model: body.model,
257+ model,
276258 });
277259 break;
278260 case "input_json_delta":
@@ -280,7 +262,7 @@
280262 throw new Error("No tool use found");
281263 }
282264 yield chatChunkFromDelta({
283- model: body.model,
265+ model,
284266 delta: {
285267 tool_calls: [
286268 {
@@ -308,13 +290,36 @@
308290 }
309291
310292 yield usageChatChunk({
311- model: body.model,
293+ model,
312294 usage: {
313295 ...usage,
314296 total_tokens: usage.completion_tokens + usage.prompt_tokens,
315297 },
316298 });
317299 }
300+
301+ async *chatCompletionStream(
302+ body: ChatCompletionCreateParamsStreaming,
303+ signal: AbortSignal,
304+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
305+ body.messages;
306+ const response = await customFetch(this.config.requestOptions)(
307+ new URL("messages", this.apiBase),
308+ {
309+ method: "POST",
310+ headers: {
311+ "Content-Type": "application/json",
312+ Accept: "application/json",
313+ "anthropic-version": "2023-06-01",
314+ "anthropic-beta": "prompt-caching-2024-07-31",
315+ "x-api-key": this.config.apiKey,
316+ },
317+ body: JSON.stringify(this._convertBody(body)),
318+ signal,
319+ },
320+ );
321+ yield* this.handleStreamResponse(response, body.model);
322+ }
318323 async completionNonStream(
319324 body: CompletionCreateParamsNonStreaming,
320325 signal: AbortSignal,
modified packages/openai-adapters/src/apis/Gemini.ts +30 −22
@@ -84,7 +84,12 @@
8484 }
8585 }
8686
87- private _convertBody(oaiBody: ChatCompletionCreateParams, url: string) {
87+ public _convertBody(
88+ oaiBody: ChatCompletionCreateParams,
89+ url: string,
90+ includeToolCallIds: boolean,
91+ overrideIsV1?: boolean,
92+ ) {
8893 const generationConfig: any = {};
8994
9095 if (oaiBody.top_p) {
@@ -101,7 +106,7 @@
101106 generationConfig.stopSequences = stop.filter((x) => x.trim() !== "");
102107 }
103108
104- const isV1API = url.includes("/v1/");
109+ const isV1API = overrideIsV1 ?? url.includes("/v1/");
105110
106111 const toolCallIdToNameMap = new Map<string, string>();
107112 oaiBody.messages.forEach((msg) => {
@@ -127,7 +132,7 @@
127132 role: "model" as const,
128133 parts: msg.tool_calls.map((toolCall) => ({
129134 functionCall: {
130- id: toolCall.id,
135+ id: includeToolCallIds ? toolCall.id : undefined,
131136 name: toolCall.function.name,
132137 args: safeParseArgs(
133138 toolCall.function.arguments,
@@ -145,7 +150,7 @@
145150 parts: [
146151 {
147152 functionResponse: {
148- id: msg.tool_call_id,
153+ id: includeToolCallIds ? msg.tool_call_id : undefined,
149154 name: functionName ?? "unknown",
150155 response: {
151156 content:
@@ -250,23 +255,9 @@
250255 };
251256 }
252257
253- async *chatCompletionStream(
254- body: ChatCompletionCreateParamsStreaming,
255- signal: AbortSignal,
256- ): AsyncGenerator<ChatCompletionChunk> {
257- const apiURL = new URL(
258- `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`,
259- this.apiBase,
260- ).toString();
261- const convertedBody = this._convertBody(body, apiURL);
262- const resp = await customFetch(this.config.requestOptions)(apiURL, {
263- method: "POST",
264- body: JSON.stringify(convertedBody),
265- signal,
266- });
267-
258+ async *handleStreamResponse(response: any, model: string) {
268259 let buffer = "";
269- for await (const chunk of streamResponse(resp as any)) {
260+ for await (const chunk of streamResponse(response as any)) {
270261 buffer += chunk;
271262 if (buffer.startsWith("[")) {
272263 buffer = buffer.slice(1);
@@ -301,11 +292,11 @@
301292 if ("text" in part) {
302293 yield chatChunk({
303294 content: part.text,
304- model: body.model,
295+ model,
305296 });
306297 } else if ("functionCall" in part) {
307298 yield chatChunkFromDelta({
308- model: body.model,
299+ model,
309300 delta: {
310301 tool_calls: [
311302 {
@@ -333,6 +324,23 @@
333324 }
334325 }
335326 }
327+
328+ async *chatCompletionStream(
329+ body: ChatCompletionCreateParamsStreaming,
330+ signal: AbortSignal,
331+ ): AsyncGenerator<ChatCompletionChunk> {
332+ const apiURL = new URL(
333+ `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`,
334+ this.apiBase,
335+ ).toString();
336+ const convertedBody = this._convertBody(body, apiURL, true);
337+ const resp = await customFetch(this.config.requestOptions)(apiURL, {
338+ method: "POST",
339+ body: JSON.stringify(convertedBody),
340+ signal,
341+ });
342+ yield* this.handleStreamResponse(resp, body.model);
343+ }
336344 completionNonStream(
337345 body: CompletionCreateParamsNonStreaming,
338346 ): Promise<Completion> {
added packages/openai-adapters/src/apis/VertexAI.ts +569 −0
@@ -0,0 +1,569 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
3+import {
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";
16+import { VertexAIConfig } from "../types.js";
17+import { chatChunk, chatCompletion, customFetch, embedding } from "../util.js";
18+import { AnthropicApi } from "./Anthropic.js";
19+import {
20+ BaseLlmApi,
21+ CreateRerankResponse,
22+ FimCreateParamsStreaming,
23+ RerankCreateParams,
24+} from "./base.js";
25+import { GeminiApi } from "./Gemini.js";
26+import { OpenAIApi } from "./OpenAI.js";
27+
28+export 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+}
modified packages/openai-adapters/src/index.ts +3 −0
@@ -14,6 +14,7 @@
1414 import { MoonshotApi } from "./apis/Moonshot.js";
1515 import { OpenAIApi } from "./apis/OpenAI.js";
1616 import { RelaceApi } from "./apis/Relace.js";
17+import { VertexAIApi } from "./apis/VertexAI.js";
1718 import { WatsonXApi } from "./apis/WatsonX.js";
1819 import { BaseLlmApi } from "./apis/base.js";
1920 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
@@ -56,6 +57,8 @@
5657 return new InceptionApi(config);
5758 case "watsonx":
5859 return new WatsonXApi(config);
60+ case "vertexai":
61+ return new VertexAIApi(config);
5962 case "llamastack":
6063 return new LlamastackApi(config);
6164 case "continue-proxy":
modified packages/openai-adapters/src/types.ts +14 −0
@@ -165,6 +165,19 @@
165165 });
166166 export type InceptionConfig = z.infer<typeof InceptionConfigSchema>;
167167
168+export const VertexAIConfigSchema = BasePlusConfig.extend({
169+ provider: z.literal("vertexai"),
170+ env: z
171+ .object({
172+ region: z.string().optional(),
173+ projectId: z.string().optional(),
174+ keyFile: z.string().optional(),
175+ keyJson: z.string().optional(),
176+ })
177+ .optional(),
178+});
179+export type VertexAIConfig = z.infer<typeof VertexAIConfigSchema>;
180+
168181 // Discriminated union
169182 export const LLMConfigSchema = z.discriminatedUnion("provider", [
170183 OpenAIConfigSchema,
@@ -179,6 +192,7 @@
179192 JinaConfigSchema,
180193 MockConfigSchema,
181194 InceptionConfigSchema,
195+ VertexAIConfigSchema,
182196 LlamastackConfigSchema,
183197 ContinueProxyConfigSchema,
184198 ]);