Calling getGenerativeModel() directly inside VisionService and TextToSpeechService duplicates firebase/ai imports, safety settings, and thinking configurations while recreating client-side GenerativeModel objects on every request and triggering unnecessary garbage collection. In this post, we extract AiModelFactory to centralize and cache model instances for multi-model routing, and we resolve two hidden caching traps: request-level generationConfig overwrites and stale AI backends after Remote Config updates.
Architecture & Mental Model
VisionService and TextToSpeechService delegate model creation and lifecycle management to AiModelFactory :
On-Demand Model Requests : VisionService calls getModel(options) with AiModelOptions , while TextToSpeechService calls getTtsModel() .
Backend Validation and Cache Eviction ( getValidBackend() ) : Before returning a model, getValidBackend() compares ConfigService.getAiBackend() against #cachedBackend .…