-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
400 lines (362 loc) · 11.9 KB
/
Copy pathroute.ts
File metadata and controls
400 lines (362 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// ! Gemini Streaming API (SSE proxy)
// todo: Ensure you have installed: pnpm add @google/genai mime && pnpm add -D @types/node
// * This route streams Live API messages from Google GenAI to the client as SSE.
import { GoogleGenAI, MediaResolution, Modality } from "@google/genai";
import type { LiveServerMessage } from "@google/genai";
import type { PostBody } from "./_requests";
export const runtime = "nodejs";
// * Using PostBody type from ./_requests
// ? Utility: format an SSE event
function sseEvent(data: unknown): string {
return `data: ${JSON.stringify(data)}\n\n`;
}
// ? Utility: standard CORS headers
function parseAllowedOrigins(): string[] | "*" {
const raw = process.env.CORS_ALLOW_ORIGINS?.trim();
if (!raw || raw === "*") return "*";
const parts = raw
.split(",")
.map((s) => s.trim())
.filter(Boolean);
return parts.length ? parts : "*";
}
function corsHeaders(origin?: string) {
const allowList = parseAllowedOrigins();
const allowCredentials = process.env.CORS_ALLOW_CREDENTIALS === "true";
const h = new Headers();
h.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
h.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
h.set("Access-Control-Max-Age", "86400");
if (allowList === "*") {
// Credentials cannot be used with wildcard per spec
h.set("Access-Control-Allow-Origin", "*");
} else {
const isAllowed = origin && allowList.includes(origin);
if (isAllowed && origin) {
h.set("Access-Control-Allow-Origin", origin);
h.set("Vary", "Origin");
}
}
if (allowCredentials) {
h.set("Access-Control-Allow-Credentials", "true");
}
return h;
}
export async function OPTIONS(req: Request): Promise<Response> {
// Preflight response
const headers = corsHeaders(req.headers.get("origin") || undefined);
return new Response(null, { status: 204, headers });
}
// ? Utility: create a configured GoogleGenAI client
function createGenAI(): GoogleGenAI | never {
const useVertex = process.env.GOOGLE_GENAI_USE_VERTEXAI === "true";
const apiVersion = process.env.GOOGLE_GENAI_API_VERSION as
| "v1"
| "v1alpha"
| undefined;
if (useVertex) {
const project = process.env.GOOGLE_CLOUD_PROJECT;
const location = process.env.GOOGLE_CLOUD_LOCATION;
if (!project || !location) {
throw new Error(
"Vertex AI mode enabled (GOOGLE_GENAI_USE_VERTEXAI=true) but GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_LOCATION is missing.",
);
}
// * Using `any` here because current @google/genai typings may not expose all documented options
// * across channels; we pass through documented fields safely for runtime while keeping TS happy.
// biome-ignore lint/suspicious/noExplicitAny: SDK options union is not fully exposed in typings
const opts: any = { vertexai: true, project, location };
if (apiVersion) opts.apiVersion = apiVersion;
return new GoogleGenAI(opts);
}
const apiKey = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error(
"Missing GOOGLE_API_KEY or GEMINI_API_KEY environment variable.",
);
}
// * Using `any` here for the same reason as above (see note).
// biome-ignore lint/suspicious/noExplicitAny: SDK options union is not fully exposed in typings
const opts: any = { apiKey };
if (apiVersion) opts.apiVersion = apiVersion;
return new GoogleGenAI(opts);
}
export async function POST(req: Request): Promise<Response> {
try {
// Initialize SDK client (supports Vertex AI or API key via env)
let ai: GoogleGenAI;
try {
ai = createGenAI();
} catch (e) {
const msg =
e instanceof Error ? e.message : "Client initialization error";
return new Response(JSON.stringify({ error: msg }), {
status: 500,
headers: { "content-type": "application/json" },
});
}
const { input, model: modelOverride } = (await req
.json()
.catch(() => ({}))) as PostBody;
const model =
modelOverride ?? "models/gemini-2.5-flash-preview-native-audio-dialog";
// Normalize input to an array of turns
const turns = Array.isArray(input)
? input
: typeof input === "string" && input.length > 0
? [input]
: ["Hello!"];
// ai created above
const stream = new TransformStream();
const writer = stream.writable.getWriter();
// Close helpers
const closeWith = async (message?: unknown) => {
try {
if (message) await writer.write(sseEvent({ type: "end", message }));
} catch (_) {
// ignore
}
try {
await writer.close();
} catch (_) {
// ignore
}
};
// Start Live session
const session = await ai.live.connect({
model,
config: {
responseModalities: [Modality.AUDIO, Modality.TEXT],
mediaResolution: MediaResolution.MEDIA_RESOLUTION_MEDIUM,
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: "Zephyr" },
},
},
contextWindowCompression: {
triggerTokens: "25600",
slidingWindow: { targetTokens: "12800" },
},
},
callbacks: {
onopen: async () => {
await writer.write(sseEvent({ type: "open" }));
},
onmessage: async (message: LiveServerMessage) => {
// Forward raw messages (client can handle text/audio inlineData/fileData)
await writer.write(sseEvent({ type: "message", payload: message }));
// If server indicates turn is complete, close the stream
if (message.serverContent?.turnComplete) {
try {
session.close();
} catch (_) {
// ignore
}
await closeWith("turn_complete");
}
},
onerror: async (e: ErrorEvent) => {
await writer.write(sseEvent({ type: "error", error: e.message }));
try {
session.close();
} catch (_) {
// ignore
}
await closeWith("error");
},
onclose: async (e: CloseEvent) => {
await writer.write(sseEvent({ type: "close", reason: e.reason }));
await closeWith("closed");
},
},
});
// Send initial turns
session.sendClientContent({ turns });
// Abort handling (if client disconnects)
const abort = req.signal;
abort.addEventListener("abort", () => {
try {
session.close();
} catch (_) {
// ignore
}
// Writer will be closed by onclose callback
});
const headers = corsHeaders(req.headers.get("origin") || undefined);
headers.set("Content-Type", "text/event-stream; charset=utf-8");
headers.set("Cache-Control", "no-cache, no-transform");
headers.set("Connection", "keep-alive");
headers.set("X-Accel-Buffering", "no"); // for nginx proxies
return new Response(stream.readable, { headers, status: 200 });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Unknown error";
const headers = corsHeaders(req.headers.get("origin") || undefined);
headers.set("content-type", "application/json");
return new Response(JSON.stringify({ error: msg }), {
status: 500,
headers,
});
}
}
// * GET handler to support EventSource clients (uses query params: input, model)
export async function GET(req: Request): Promise<Response> {
try {
// Initialize SDK client (supports Vertex AI or API key via env)
let ai: GoogleGenAI;
try {
ai = createGenAI();
} catch (e) {
const msg =
e instanceof Error ? e.message : "Client initialization error";
const headers = corsHeaders(req.headers.get("origin") || undefined);
headers.set("content-type", "application/json");
return new Response(JSON.stringify({ error: msg }), {
status: 500,
headers,
});
}
const url = new URL(req.url);
// Health check: verify configuration AND perform a real API check for API key mode
if (url.searchParams.get("health") === "1") {
const headers = corsHeaders(req.headers.get("origin") || undefined);
try {
const useVertex = process.env.GOOGLE_GENAI_USE_VERTEXAI === "true";
if (useVertex) {
// For Vertex AI we validate required envs are present; a full token check requires ADC and scopes.
const project = process.env.GOOGLE_CLOUD_PROJECT;
const location = process.env.GOOGLE_CLOUD_LOCATION;
if (!project || !location) {
headers.set("content-type", "application/json");
return new Response(
JSON.stringify({
error: "Missing GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_LOCATION",
}),
{ status: 500, headers },
);
}
return new Response(null, { status: 204, headers });
}
const apiKey = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;
if (!apiKey) {
headers.set("content-type", "application/json");
return new Response(
JSON.stringify({
error: "Missing GOOGLE_API_KEY or GEMINI_API_KEY",
}),
{ status: 500, headers },
);
}
const ver = (process.env.GOOGLE_GENAI_API_VERSION || "v1").replace(
/^v(\d)(.*)$/,
"v$1$2",
);
const checkUrl = `https://generativelanguage.googleapis.com/${ver}/models?key=${encodeURIComponent(apiKey)}`;
const resp = await fetch(checkUrl, {
method: "GET",
cache: "no-store",
});
if (resp.ok) {
return new Response(null, { status: 204, headers });
}
headers.set("content-type", "application/json");
const text = await resp.text().catch(() => "");
return new Response(
JSON.stringify({
error: `Google API health failed: ${resp.status}`,
body: text.slice(0, 300),
}),
{ status: 500, headers },
);
} catch (e) {
headers.set("content-type", "application/json");
return new Response(JSON.stringify({ error: (e as Error).message }), {
status: 500,
headers,
});
}
}
const modelOverride = url.searchParams.get("model") ?? undefined;
const input = url.searchParams.getAll("input");
const model =
modelOverride ?? "models/gemini-2.5-flash-preview-native-audio-dialog";
const turns = input.length > 0 ? input : ["Hello!"];
const stream = new TransformStream();
const writer = stream.writable.getWriter();
const sseEventLocal = (data: unknown) =>
`data: ${JSON.stringify(data)}\n\n`;
const closeWith = async (message?: unknown) => {
try {
if (message)
await writer.write(sseEventLocal({ type: "end", message }));
} catch {}
try {
await writer.close();
} catch {}
};
const session = await ai.live.connect({
model,
config: {
responseModalities: [Modality.AUDIO, Modality.TEXT],
mediaResolution: MediaResolution.MEDIA_RESOLUTION_MEDIUM,
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: "Zephyr" } },
},
contextWindowCompression: {
triggerTokens: "25600",
slidingWindow: { targetTokens: "12800" },
},
},
callbacks: {
onopen: async () => {
await writer.write(sseEventLocal({ type: "open" }));
},
onmessage: async (message: LiveServerMessage) => {
await writer.write(
sseEventLocal({ type: "message", payload: message }),
);
if (message.serverContent?.turnComplete) {
try {
session.close();
} catch {}
await closeWith("turn_complete");
}
},
onerror: async (e: ErrorEvent) => {
await writer.write(
sseEventLocal({ type: "error", error: e.message }),
);
try {
session.close();
} catch {}
await closeWith("error");
},
onclose: async (e: CloseEvent) => {
await writer.write(
sseEventLocal({ type: "close", reason: e.reason }),
);
await closeWith("closed");
},
},
});
session.sendClientContent({ turns });
req.signal.addEventListener("abort", () => {
try {
session.close();
} catch {}
});
const headers = corsHeaders(req.headers.get("origin") || undefined);
headers.set("Content-Type", "text/event-stream; charset=utf-8");
headers.set("Cache-Control", "no-cache, no-transform");
headers.set("Connection", "keep-alive");
headers.set("X-Accel-Buffering", "no");
return new Response(stream.readable, { headers, status: 200 });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Unknown error";
const headers = corsHeaders(req.headers.get("origin") || undefined);
headers.set("content-type", "application/json");
return new Response(JSON.stringify({ error: msg }), {
status: 500,
headers,
});
}
}