Vertex AI & Model Routing — 8-Model Matrix, Thinking Calculus, Visual Synthesis & Auth Resilience
Document ID: YPG-AI-004 | Index: docs/README.md
Cloud Endpoint: Google Cloud Vertex AI (project: 'ids-hybrid-model', location: 'global', @google/genai ^3.6.1)
Primary Modules: src/config/models.mjs, src/services/vertexAiService.mjs, src/services/gameGeneratorService.mjs
1. Vertex AI Engineering Topology
All language, reasoning, code-synthesis, forensic-repair, and multimodal image-synthesis operations execute directly against Google Cloud Vertex AI (vertexai: true, project: env.vertexProject || 'ids-hybrid-model', location: env.vertexLocation || 'global').
Rather than routing every workload through a single monolithic model, YourPlayground.games separates active creative game synthesis from forensic structural repair and multimodal raster synthesis:
VERTEX_DEFAULT_MODEL = 'gemini-4-neon'(Active Game Coding Default): Optimized for fast token generation, multi-step agentic iteration, and nativeXHIGHreasoning depth across HTML5 Canvas 2D, Phaser.js 3.90, and Three.js r160 single-file architectures.VERTEX_REPAIR_MODEL = 'gemini-4-carbon'(Forensic 1-Shot Repair Default): Invoked automatically at low temperature (temperature: 0.3) only when first-pass output fails linear-time HTML5 structural verification or Node.js V8vm.Scriptsyntax compilation.DEFAULT_IMAGE_MODEL_ID = 'gemini-nano-banana-2.1'(Fast Sprites & Cover Art Default): Paired withgemini-3-pro-image(1K–4Kstudio key art) for parallel non-blocking cover (16:9) and sprite (1:1) synthesis.
2. Complete 8-Model Text & Code Matrix
Defined in TEXT_MODELS (src/config/models.mjs lines 1–98) and exposed dynamically via GET /api/config, SSR Studio <select data-testid="model-select">, and /.well-known/ai-context.json:
| Model ID | Studio Label | Series Tier | Studio Badge | Native supportedThinkingLevels | Default Thinking | Engineering Role & Ideal Game Archetypes |
|---|---|---|---|---|---|---|
gemini-4-neon (Default) | Gemini 4 Neon | Gemini 4 Frontier | Active Game Coding · XHIGH | AUTO, LOW, MEDIUM, HIGH, XHIGH | MEDIUM | Primary active game coding, multi-step iteration, and fast HTML5 / Phaser / Three.js loops with native XHIGH support. |
gemini-4-carbon (Repair) | Gemini 4 Carbon | Gemini 4 Frontier | Deep Architecture & Repair | AUTO, LOW, MEDIUM, HIGH | MEDIUM | Deep structural architecture, complex rigid-body/orbital physics, and automatic 1-shot forensic validation repair. |
gemini-4-hydrogen | Gemini 4 Hydrogen | Gemini 4 Frontier | Fast Reasoning | AUTO, LOW, MEDIUM, HIGH, XHIGH | MEDIUM | High-depth spatial geometry, Three.js 3D WebGL lighting/camera rigs, and multi-wave enemy formations with native XHIGH. |
gemini-4-argon | Gemini 4 Argon | Gemini 4 Frontier | Experimental | AUTO, LOW, MEDIUM, HIGH | MEDIUM | Experimental mechanics, procedural arena generation, and emergent arcade rulesets. |
gemini-3.8-flash | Gemini 3.8 Flash | Gemini 3 Series | Ultra Fast | AUTO, LOW, MEDIUM, HIGH | MEDIUM | Ultra-low-latency rapid arcade prototyping and twitch reflex shooters. |
gemini-3.7-flash | Gemini 3.7 Flash | Gemini 3 Series | Balanced | AUTO, LOW, MEDIUM, HIGH | MEDIUM | Balanced synthesis speed and clean 2D Canvas / Phaser.js sprite state machines. |
gemini-3.6-flash | Gemini 3.6 Flash | Gemini 3 Series | Streamlined | AUTO, MINIMAL, LOW, MEDIUM, HIGH | MEDIUM | Streamlined single-screen arcade builds supporting native ultra-fast MINIMAL reasoning. |
gemini-3.1-pro-preview | Gemini 3.1 Pro | Gemini 3 Series | Deep Pro | AUTO, LOW, MEDIUM, HIGH | MEDIUM | Deterministic grid puzzles, optical/circuit routing logic, and turn-based tactical systems (aliases: gemini-3.1-pro). |
Registry Normalization (resolveTextModel)
resolveByRegistry() (models.mjs lines 161–181) strips full Vertex resource prefixes (projects/{p}/locations/{l}/publishers/google/models/), collapses whitespace, and matches case-insensitively against id, label, and aliases so API callers and CLI scripts can pass either canonical IDs (gemini-4-neon) or full Vertex publisher paths.
3. Thinking-Level Clamping Calculus & Runtime Fallback
3.1 Formal Clamping Function C(m, τ)
Different Vertex AI model families accept distinct subsets S(m) \subseteq \AUTO, MINIMAL, LOW, MEDIUM, HIGH, XHIGH\ in config.thinkingConfig.thinkingLevel. Sending an unsupported enum value (such as XHIGH to gemini-4-carbon, or MINIMAL to gemini-4-neon) without clamping would trigger a 400 INVALID_ARGUMENT rejection from the Vertex AI endpoint.
buildThinkingConfig(modelId, requestedLevel) (models.mjs lines 202–224) computes the exact deterministic projection:
$$
\mathcal{C}(m, \tau) = \begin{cases}
\bot \;\;(\text{omit } \texttt{thinkingConfig}) & \text{if } \tau \in \{\texttt{undefined}, \texttt{null}, \texttt{""}, \texttt{"AUTO"}, \texttt{"DEFAULT"}\} \\
\{ \texttt{thinkingLevel}: \tau \} & \text{if } \tau \in \mathcal{S}(m) \\
\{ \texttt{thinkingLevel}: \texttt{"LOW"} \} & \text{if } \tau \in \{\texttt{"MINIMAL"}, \texttt{"NONE"}, \texttt{"OFF"}\} \land \tau \notin \mathcal{S}(m) \\
\{ \texttt{thinkingLevel}: \texttt{"HIGH"} \} & \text{if } \tau = \texttt{"XHIGH"} \land \tau \notin \mathcal{S}(m) \\
\{ \texttt{thinkingLevel}: \tau_{\text{default}}(m) \} & \text{otherwise } (\tau_{\text{default}}(m) = \texttt{"MEDIUM"})
\end{cases}
$$
Furthermore, generateText() (vertexAiService.mjs lines 452–470) explicitly deletes any accidental thinkingBudget property whenever thinkingConfig is constructed, preventing mutual-exclusivity 400 errors between thinkingLevel and legacy thinkingBudget fields in @google/genai.
3.2 Two-Layer Thinking Rejection Recovery & Thought-Part Filtering
- Graceful
AUTORetry on Endpoint Rejection: If an upstream preview endpoint transiently rejectsthinkingConfig(HTTP 400or/thinking|INVALID_ARGUMENT/i, tested viaisThinkingConfigRejection(err)while excluding401/ADC auth errors),generateText()automatically retries once withbuildConfig(false)(omittingthinkingConfig) and returnsusedThinkingFallback: true, thinkingLevel: 'AUTO'. - Thought-Token Separation (
!p.thought): Reasoning models emit internal chain-of-thought parts marked withpart.thought === truealongside final code output parts.generateText()filtersresponse.candidates[0].content.partsstrictly via:
const nonThoughtPartsText = parts
.filter((p) => typeof p?.text === 'string' && !p.thought)
.map((p) => p.text)
.join('');
guaranteeing that internal reasoning traces never leak into extracted HTML5 documents.
4. Token Budget Allocation (maxOutputTokens >= 32768)
A major root cause of broken LLM-generated games is mid-script truncation when reasoning tokens + HTML/CSS/JS tokens exceed small default output caps (such as 2048 or 8192 tokens).
generateText() enforces a hard lower bound on every synthesis and repair call (vertexAiService.mjs line 464):
$$
\texttt{cfg.maxOutputTokens} = \max\!\big(32768,\; \lfloor \text{Number}(\text{requestedMaxOutputTokens}) \rfloor\big)
$$
Paired with system-prompt conciseness guidance (~140–240 lines of cohesive, zero-boilerplate game code in buildEngineSystemPrompt), a 32,768-token ceiling provides > 4\times safety margin even under XHIGH reasoning chains.
5. Multimodal Visual Synthesis (Nano Banana 2.1 & Gemini 3 Pro Image)
Configured in IMAGE_MODELS (models.mjs lines 114–133) and executed via generateImage() (vertexAiService.mjs lines 543–635):
| Image Model ID | Studio Label | Aliases | Resolution Tiers (ALLOWED_IMAGE_SIZES) | Allowed Aspect Ratios | Primary Studio Usage |
|---|---|---|---|---|---|
gemini-nano-banana-2.1 (Default) | Nano Banana 2.1 | nano-banana-2.1 | 1K, 2K, 4K | 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 21:9 | Fast parallel 16:9 game cover thumbnails, 1:1 in-game hero sprites (/api/games/:slug/sprites), and cropped reference-guided UI assets. |
gemini-3-pro-image | Gemini 3 Pro Image | gemini-3-pro-image-preview | 1K, 2K, 4K | 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 21:9 | High-detail studio hero panoramas (public/creatives/hero-studio.png), category key art (public/creatives/categories/*.png), and flagship showcase covers. |
- MIME Normalization:
normalizeImageMimeType()normalizes'png','jpg','jpeg', or unsupported'image/webp'defaults safely to'image/png'or'image/jpeg'(strict: truethrows400 UNSUPPORTED_IMAGE_MIMEwhen direct callers require strict validation). - Non-Blocking Cover/Sprite Fault Isolation: During
generateAndSaveGame(),codeTask,coverTask, andspriteTaskrun concurrently viaPromise.all(). If an optional image generation call hits a transient quota limit,.catch(() => null)degrades gracefully to the category banner fallback (categoryObj.bannerUrl) and procedural Canvas/Phaser vector sprites rather than aborting a valid playable game build.
6. Credential Resilience: 45-Minute Cached gcloud CLI Fallback on ADC invalid_rapt
6.1 The Workstation & Cloud Reauth Problem
On developer workstations and long-running staging hosts using Google Cloud Application Default Credentials (~/.config/gcloud/application_default_credentials.json), Google Workspace RAPT (Risk-based Authentication / Reauth Policy Token) expiration causes @google/genai's default google-auth-library ADC client to fail with invalid_rapt, invalid_grant, or reauth related error even when the user's active gcloud CLI session remains authenticated!
6.2 State Machine & Single-Flight Refresh Protocol
vertexAiService.mjs (lines 31–324) implements an automatic, zero-downtime credential failover state machine:
sequenceDiagram
autonumber
participant Caller as gameGeneratorService
participant Exec as executeVertexGenerateContent
participant ADC as Primary GoogleGenAI (ADC)
participant Cache as liveAuthFallbackState<br/>(TTL: 45m, inflightPromise)
participant CLI as gcloud auth print-access-token<br/>(Timeout: 15s, windowsHide: true)
participant Fallback as Gcloud-Backed GoogleGenAI
Caller->>Exec: generateContent(requestPayload)
alt preferGcloudAuth == false
Exec->>ADC: primaryClient.models.generateContent()
alt ADC Succeeds
ADC-->>Exec: Vertex Response
else Error matches /invalid_rapt|invalid_grant|reauth related error/i
Exec->>Cache: Set preferGcloudAuth = true & request getValidGcloudToken()
Cache->>CLI: execFile(cmd.exe /c gcloud.cmd auth print-access-token --quiet)
CLI-->>Cache: Bearer Token (cached for 45 * 60 * 1000 ms)
Exec->>Fallback: gcloudClient.models.generateContent()
Fallback-->>Exec: Vertex Response
end
else preferGcloudAuth == true
Exec->>Cache: getValidGcloudToken(forceRefresh: false)
Note over Cache: Reuses cached token if now < expiresAt<br/>or awaits shared inflightPromise under concurrency
Exec->>Fallback: gcloudClient.models.generateContent()
alt 401 UNAUTHENTICATED / ACCESS_TOKEN_EXPIRED
Exec->>Cache: getValidGcloudToken(forceRefresh: true)
Cache->>CLI: Mint fresh access token
Exec->>Fallback: Retry gcloudClient.models.generateContent()
end
Fallback-->>Exec: Vertex Response
end
Exec-->>Caller: Extracted non-thought output
Key Resilience Properties
- 45-Minute Token Cache (
GCLOUD_TOKEN_TTL_MS = 2,700,000 ms): Google Cloud OAuth2 access tokens have a 60-minute lifetime; caching for 45 minutes eliminates subprocess spawn overhead on subsequent requests while maintaining a 15-minute expiry safety buffer. - Single-Flight Concurrency Coalescing (
state.inflightPromise): WhencodeTask,coverTask, andspriteTaskexecute in parallel viaPromise.all()during an ADC failover, all three await the exact sameinflightPromise, spawninggcloudonce rather than three times concurrently. - Cross-Platform Subprocess Hardening: On Windows (
process.platform === 'win32'), invokescmd.exe /d /s /c "gcloud.cmd auth print-access-token --quiet"withwindowsHide: true,timeout: 15000, and strict whitespace/empty token validation before injectingAuthorization: Bearer ${token}via a customgoogleAuthOptions.authClient. - Exponential Backoff on Transient Upstream Errors:
runWithTransientRetry()wrapsexecuteVertexGenerateContent()with up tomaxRetries = 2retries (baseDelayMs = 1200 ms, delays1.2 sand2.4 s) strictly on transient statuses (429,500,502,503,504,RESOURCE_EXHAUSTED,UNAVAILABLE,DEADLINE_EXCEEDED,ECONNRESET), never retrying deterministic400validation errors.
7. Prompt-to-AAA Genre Blueprints, Static Quality Scoring & 121.games Syndication
Before invoking gemini-4-neon (or gemini-4-carbon repair), gameGeneratorService.mjs routes every user prompt through the 10-Archetype Prompt-to-AAA Blueprint Compiler (src/services/genreBlueprintService.mjs), injects deterministic articulated rig / input parity / locked 60 FPS / WebAudio blueprints into buildEngineSystemPrompt(), and evaluates every sanitized HTML5 output with scoreGeneratedGameQuality(html, engine) (0..100 diagnostics exposed directly in generation metadata).
For the full 10-archetype blueprint matrix, static quality rubric, GET /api/syndication/121games read-only partner feed, and dual YourPlaygroundSDK / 121SDK bridge specification, see PROMPT_TO_ENGINE_BLUEPRINTS_AND_121_SYNDICATION.md.