fix: lazy Gemini client init — server starts without GEMINI env vars

The GoogleGenAI client threw at module load if AI_INTEGRATIONS_GEMINI_BASE_URL
was unset, crashing the VPS service. Now uses lazy singleton (throws on first use).
Routes return 503 gracefully when Gemini is not configured on the host.
This commit is contained in:
Replit Agent
2026-03-20 02:43:52 +00:00
parent e86dab0d65
commit 67e9f0fd64
2 changed files with 33 additions and 34 deletions

View File

@@ -1,21 +1,38 @@
import { GoogleGenAI } from "@google/genai";
if (!process.env.AI_INTEGRATIONS_GEMINI_BASE_URL) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_BASE_URL must be set. Did you forget to provision the Gemini AI integration?",
);
function createClient(): GoogleGenAI {
if (!process.env.AI_INTEGRATIONS_GEMINI_BASE_URL) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_BASE_URL must be set. Did you forget to provision the Gemini AI integration?",
);
}
if (!process.env.AI_INTEGRATIONS_GEMINI_API_KEY) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_API_KEY must be set. Did you forget to provision the Gemini AI integration?",
);
}
return new GoogleGenAI({
apiKey: process.env.AI_INTEGRATIONS_GEMINI_API_KEY,
httpOptions: {
apiVersion: "",
baseUrl: process.env.AI_INTEGRATIONS_GEMINI_BASE_URL,
},
});
}
if (!process.env.AI_INTEGRATIONS_GEMINI_API_KEY) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_API_KEY must be set. Did you forget to provision the Gemini AI integration?",
);
let _ai: GoogleGenAI | null = null;
export function getAi(): GoogleGenAI {
if (!_ai) {
_ai = createClient();
}
return _ai;
}
export const ai = new GoogleGenAI({
apiKey: process.env.AI_INTEGRATIONS_GEMINI_API_KEY,
httpOptions: {
apiVersion: "",
baseUrl: process.env.AI_INTEGRATIONS_GEMINI_BASE_URL,
export const ai: GoogleGenAI = new Proxy({} as GoogleGenAI, {
get(_target, prop: keyof GoogleGenAI) {
return getAi()[prop];
},
});

View File

@@ -1,28 +1,10 @@
import { GoogleGenAI, Modality } from "@google/genai";
if (!process.env.AI_INTEGRATIONS_GEMINI_BASE_URL) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_BASE_URL must be set. Did you forget to provision the Gemini AI integration?",
);
}
if (!process.env.AI_INTEGRATIONS_GEMINI_API_KEY) {
throw new Error(
"AI_INTEGRATIONS_GEMINI_API_KEY must be set. Did you forget to provision the Gemini AI integration?",
);
}
export const ai = new GoogleGenAI({
apiKey: process.env.AI_INTEGRATIONS_GEMINI_API_KEY,
httpOptions: {
apiVersion: "",
baseUrl: process.env.AI_INTEGRATIONS_GEMINI_BASE_URL,
},
});
import { Modality } from "@google/genai";
import { getAi } from "../client.js";
export async function generateImage(
prompt: string
): Promise<{ b64_json: string; mimeType: string }> {
const ai = getAi();
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-image",
contents: [{ role: "user", parts: [{ text: prompt }] }],