Skip to main content
Developer & Creator Documentation

Vertex AI & Model Routing — 8-Model Matrix, Thinking Calculus, Visual Synthesis & Auth Resilience

All language, reasoning, code-synthesis, forensic-repair, and multimodal image-synthesis operations execute directly against Google Cloud Vertex AI (vertexai: true, project: env.vertexP

Open AI Studio Direct-Answer FAQ Hub Machine-Readable Corpus (/llms-full.txt)

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 native XHIGH reasoning 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 V8 vm.Script syntax compilation.
  • DEFAULT_IMAGE_MODEL_ID = 'gemini-nano-banana-2.1' (Fast Sprites & Cover Art Default): Paired with gemini-3-pro-image (1K–4K studio 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 IDStudio LabelSeries TierStudio BadgeNative supportedThinkingLevelsDefault ThinkingEngineering Role & Ideal Game Archetypes
gemini-4-neon (Default)Gemini 4 NeonGemini 4 FrontierActive Game Coding · XHIGHAUTO, LOW, MEDIUM, HIGH, XHIGHMEDIUMPrimary active game coding, multi-step iteration, and fast HTML5 / Phaser / Three.js loops with native XHIGH support.
gemini-4-carbon (Repair)Gemini 4 CarbonGemini 4 FrontierDeep Architecture & RepairAUTO, LOW, MEDIUM, HIGHMEDIUMDeep structural architecture, complex rigid-body/orbital physics, and automatic 1-shot forensic validation repair.
gemini-4-hydrogenGemini 4 HydrogenGemini 4 FrontierFast ReasoningAUTO, LOW, MEDIUM, HIGH, XHIGHMEDIUMHigh-depth spatial geometry, Three.js 3D WebGL lighting/camera rigs, and multi-wave enemy formations with native XHIGH.
gemini-4-argonGemini 4 ArgonGemini 4 FrontierExperimentalAUTO, LOW, MEDIUM, HIGHMEDIUMExperimental mechanics, procedural arena generation, and emergent arcade rulesets.
gemini-3.8-flashGemini 3.8 FlashGemini 3 SeriesUltra FastAUTO, LOW, MEDIUM, HIGHMEDIUMUltra-low-latency rapid arcade prototyping and twitch reflex shooters.
gemini-3.7-flashGemini 3.7 FlashGemini 3 SeriesBalancedAUTO, LOW, MEDIUM, HIGHMEDIUMBalanced synthesis speed and clean 2D Canvas / Phaser.js sprite state machines.
gemini-3.6-flashGemini 3.6 FlashGemini 3 SeriesStreamlinedAUTO, MINIMAL, LOW, MEDIUM, HIGHMEDIUMStreamlined single-screen arcade builds supporting native ultra-fast MINIMAL reasoning.
gemini-3.1-pro-previewGemini 3.1 ProGemini 3 SeriesDeep ProAUTO, LOW, MEDIUM, HIGHMEDIUMDeterministic 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

  1. Graceful AUTO Retry on Endpoint Rejection: If an upstream preview endpoint transiently rejects thinkingConfig (HTTP 400 or /thinking|INVALID_ARGUMENT/i, tested via isThinkingConfigRejection(err) while excluding 401/ADC auth errors), generateText() automatically retries once with buildConfig(false) (omitting thinkingConfig) and returns usedThinkingFallback: true, thinkingLevel: 'AUTO'.
  2. Thought-Token Separation (!p.thought): Reasoning models emit internal chain-of-thought parts marked with part.thought === true alongside final code output parts. generateText() filters response.candidates[0].content.parts strictly 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 IDStudio LabelAliasesResolution Tiers (ALLOWED_IMAGE_SIZES)Allowed Aspect RatiosPrimary Studio Usage
gemini-nano-banana-2.1 (Default)Nano Banana 2.1nano-banana-2.11K, 2K, 4K1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 21:9Fast 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-imageGemini 3 Pro Imagegemini-3-pro-image-preview1K, 2K, 4K1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 21:9High-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: true throws 400 UNSUPPORTED_IMAGE_MIME when direct callers require strict validation).
  • Non-Blocking Cover/Sprite Fault Isolation: During generateAndSaveGame(), codeTask, coverTask, and spriteTask run concurrently via Promise.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

  1. 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.
  2. Single-Flight Concurrency Coalescing (state.inflightPromise): When codeTask, coverTask, and spriteTask execute in parallel via Promise.all() during an ADC failover, all three await the exact same inflightPromise, spawning gcloud once rather than three times concurrently.
  3. Cross-Platform Subprocess Hardening: On Windows (process.platform === 'win32'), invokes cmd.exe /d /s /c "gcloud.cmd auth print-access-token --quiet" with windowsHide: true, timeout: 15000, and strict whitespace/empty token validation before injecting Authorization: Bearer ${token} via a custom googleAuthOptions.authClient.
  4. Exponential Backoff on Transient Upstream Errors: runWithTransientRetry() wraps executeVertexGenerateContent() with up to maxRetries = 2 retries (baseDelayMs = 1200 ms, delays 1.2 s and 2.4 s) strictly on transient statuses (429, 500, 502, 503, 504, RESOURCE_EXHAUSTED, UNAVAILABLE, DEADLINE_EXCEEDED, ECONNRESET), never retrying deterministic 400 validation 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.