From 0c85c840a6c6c14733568b34eeb746ff3e4b10df Mon Sep 17 00:00:00 2001 From: Jeff Emmett Date: Thu, 18 Dec 2025 20:07:27 -0500 Subject: [PATCH] fix: use lazy initialization for Gemini SDK to use runtime env vars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK was being initialized at module load time with the build-time env var (empty string), instead of the runtime env var. Changed to lazy initialization pattern that creates the client on first use. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- web/lib/gemini.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/web/lib/gemini.ts b/web/lib/gemini.ts index 33ffaa4..4ca7ff7 100644 --- a/web/lib/gemini.ts +++ b/web/lib/gemini.ts @@ -1,6 +1,18 @@ import { GoogleGenerativeAI } from "@google/generative-ai"; -const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || ""); +// Lazy initialization to ensure runtime env var is used (not build-time) +let _genAI: GoogleGenerativeAI | null = null; + +function getGenAI(): GoogleGenerativeAI { + if (!_genAI) { + const apiKey = process.env.GEMINI_API_KEY; + if (!apiKey) { + throw new Error("GEMINI_API_KEY environment variable is not set"); + } + _genAI = new GoogleGenerativeAI(apiKey); + } + return _genAI; +} export interface PageOutline { pageNumber: number; @@ -39,7 +51,7 @@ export async function generateOutline( style: string, tone: string ): Promise { - const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" }); + const model = getGenAI().getGenerativeModel({ model: "gemini-2.0-flash" }); const prompt = `You are creating an 8-page mycro-zine (mini DIY zine that folds from a single sheet of paper). @@ -92,7 +104,7 @@ export async function generatePageImage( feedback?: string ): Promise { // Use Gemini's image generation (Imagen 3 via Gemini API) - const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash-exp" }); + const model = getGenAI().getGenerativeModel({ model: "gemini-2.0-flash-exp" }); const styleDesc = STYLE_PROMPTS[style] || STYLE_PROMPTS["punk-zine"]; const toneDesc = TONE_PROMPTS[tone] || TONE_PROMPTS["rebellious"]; @@ -148,7 +160,7 @@ export async function regeneratePageWithFeedback( style: string, tone: string ): Promise<{ updatedOutline: PageOutline; imageUrl: string }> { - const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" }); + const model = getGenAI().getGenerativeModel({ model: "gemini-2.0-flash" }); // First, update the outline based on feedback const prompt = `You are refining a zine page based on user feedback.