Skip to main content
← All writingKylan Thomson

Google Cloud · Generative AI

A Gemini Director for a Card Game on Cloud Run

The video model needs to be told what a Tail Whip looks like. A Gemini pass reads each card once, illustration included, and writes the shot list, and it authenticates as the Cloud Run service account so there is nothing to leak.

Published
Reading time
9 minutes
Project
Pokémon TCG Live Attacks case study

The video model in Pokémon TCG Live Attacks needs to be told what a Tail Whip looks like. The first version told it with regex tables, an instrument plus an action, and that is deterministic and free and still the fallback. But a table cannot know that a card's Hydro Pump grows with the Water Energy stacked on it, that its flavour text describes a creature that hovers, or that Rain Dance is not a strike at all. A Gemini pass reads each card once, illustration included, and writes the shot list. It runs on Cloud Run with no API key anywhere. This is how it works.

The director is one component of a larger generation pipeline that is described in the case study and the article on cache warming. Here I stay inside the one file that talks to Gemini, because it is where the prompt-design decisions live.

Four passes, four cache keys

The four Gemini passes, what each is shown, and what it writes
PassCachedInputOutput fieldsTemperature
Art readOnce per cardThe illustration aloneSetting, light, palette, bearing, signature, hand, motion, framing0.2
DirectionOnce per card and attackCard text, effects, illustrationMode, body, energy look, charge-up, choreography, impact, camera, pronunciations1.0
StagingOnce per kind of playThe resolution, both cards, the match so farApproach, impact, reaction, camera, two spoken lines1.0
PronunciationOnce per name, in batches of 60A list of namesA respelling per name, or none if it is an English word0
The four Gemini passes. Each is cached at a different granularity, each has a different temperature, and each is optional: a null answer means the deterministic tables are used for that field.

The art read: describe the picture, not the species

Every direction call is shown the illustration but asked about the attack, so what it says about the picture is a by-product, and the portrait prompts that actually put a card's world on screen never saw any of it. The art read is a separate pass, one per card, that looks at nothing but the painting and returns eight fields: setting, light, palette, bearing, signature, hand, motion, framing. The instruction is explicit that it must describe what is painted and not what it knows about the species: if the artist put a Fire type in a snowfield, the answer is a snowfield. It runs at a low temperature, because a description should read the same way twice, and a read with neither a setting nor a bearing is rejected as a misread instruction rather than cached.

The direction: once per card and attack

The direction pass is handed the card text, the energy cost, the printed damage, one plain-English line per parsed effect (“using it consumes two of the Pokémon's own Water energy, which should visibly burn away”), the arena, and the inline illustration, and returns ten fields: the pronunciations of the Pokémon and attack names, a mode, a body, how the energy looks in long and short form, the charge-up beat, the choreography, the impact on the scene, and the camera move.

Two of its seven hard constraints are correctness rules rather than style. Never use quotation marks, because the video model speaks any quoted text it finds in a prompt and another part of the prompt owns speech. And the attacker faces the camera because the opponent stands where the camera is; never send an attack into the distance, because every clip is pinned between two portraits with the camera standing between the two Pokémon. The sixth constraint is the art read in instruction form: direct only movements the painted body can make, and where the picture and your idea of the species disagree, the picture wins.

// species.ts infers a body from HP, retreat cost and flavour text, which is
// a good guess and no more; the director has seen this printing's own
// artwork, so where it describes the body there, that is the real one.
const build = direction?.body
  ? capitalise(direction.body).replace(/.?$/, ".")
  : speciesNotes(attacker);
prompt.ts: the director's body description beats the table's guess, because it is the only thing in the pipeline that has looked at the illustration.

Four shapes of attack

Every clip used to be a blow: charge up, hurl something at the camera, land it. That is right for most attacks and wrong for a whole class of them. Ninetales' Lure does no damage and throws nothing; staged as a strike it came out as a generic fire blast with the card text contradicting the picture. So the director chooses a mode from the rules text, trusting the text over the name: strike, where something crosses the distance and hits; snare, where the attack reaches out and takes hold; field, where it changes the place itself; self, where it turns inward. Only three fragments of the prompt differ between them, the lead, the form, and how the defender meets it. The rest of the shot grammar is invariant, because the clip is still one continuous move from the attacker's ground to the defender's.

The staging: once per kind of play

A direction writes an attack: how Fire Spin always looks. That is why it is good and also its ceiling, because it cannot know that this particular Fire Spin ends the match, or lands on a defender with 20 HP left, or hits a weakness. Over the twenty clips of a match, every glancing hit rocking the scene in the same words is what makes a reel read as generated rather than filmed. The staging pass takes the resolved outcome, both cards, the story of the match so far, and the direction, and writes six fields: approach, impact, reaction, camera, and two spoken lines of six to twelve words each.

return [r.attackerCardId, attackName, r.defenderCardId,
        impactWeight(r),   // glancing | solid | heavy | devastating
        outcome,           // fizzled | ko | nearly | survived
        modifier,          // weakness | resistance | shielded | plain
        conditions, finish, storyDigest, "v3"].join("__");
director.ts: the staging cache key. Buckets rather than exact numbers, so the shots that should differ do and the ones that should not stay identical.

The one instruction doing the most work is a calibration paragraph: a hit that took a sliver off a healthy Pokémon must not look like a finisher, and if the model writes a graze and a killing blow at the same pitch it has done nothing and should have written less. Including a digest of the match story in the key means far fewer cache hits than the visual fields alone would get, and it largely retires the clip-reuse cache that keyed on the finished prompt. That is the trade: repeated matchups stop replaying the identical clip.

Pronunciation: keyed by name, not by card

Video models with native speech read a name as English, and Arcanine is not pronounced the way English would. The first version asked for a respelling inside each direction, and it drifted: two calls about the same Charizard could respell it two ways, and a clip whose attacker was directed by one and defender by the other said the same name twice, differently, in one breath. It was also keyed wrong, because a respelling belongs to a name, not to a card and attack. The pronunciation pass now takes every name in a match in batches of sixty at temperature zero, caches by name, and stores a null for names that are already English words so they are never asked about again. The hyphenated, capitalised form is for people; the video model gets one lowercase run-on word spelled the way it sounds.

How a partial answer merges

Every field falls back independently. The energy look falls back to a per-type table, the mode to strike, the camera to the direction's camera or a table, the body to the inference from HP and flavour text. The staging pass's approach is added to the charge-up beat rather than replacing the attack's own, which is still its signature. Impact is a hybrid: the direction's sentence carries the character of the hit, and a suffix keyed to the impact weight carries its force, because the direction wrote what the attack does to the world once, outcome-blind, and the same move landing for 10 damage and for a knockout must not shake the screen equally hard.

A response only counts at all if it has the one field the tables are weakest at: choreography for a direction, reaction for a staging. Everything is sanitised on the way in, quotes and markdown stripped because they would be spoken aloud, fields truncated at a word boundary, a respelling rejected if it has lost the shape of a name. A well-formed but unusable answer is recorded as a skip so it is not retried forever.

The warm path An architecture diagram generated by Archify. Hand diff · after every action · Architecture component · turns before any attack · React Hand diff after every action turns before any attack POST /api/portraits · warmDirections · warmPortraits · Cloud Run · Next.js POST /api/portraits warmDirections · warmPortraits Gemini director · art read · direction · names · Architecture component · Google Gemini Gemini director art read · direction · names Image edit · battle, then hurt and fainted · Architecture component Image edit battle, then hurt and fainted Firestore caches · keyed by card + version · Cloud Run · once per Pokémon, ever · Firebase Firestore caches keyed by card + version once per Pokémon, ever Attack predictor · likely attack · hover · CPU replay · Architecture component · React Attack predictor likely attack · hover · CPU replay startGeneration · two cache reads, one request · Cloud Run · Next.js startGeneration two cache reads, one request fal.ai queue · video · CPU clips reused ×3 · Architecture component fal.ai queue video · CPU clips reused ×3 new card ids every printed attack portraits write write prepare(signature) read submit, poll Cloud Run Legend Frontend Backend Database External
Where the director sits. Directions and art reads are warmed the moment a card reaches a hand, alongside the portraits, and land in Firestore keyed by card and version; at attack time the direction is a cache read, and only the staging pass runs on the path to the clip.

Running it on Cloud Run with no key

  1. Credentials resolve once. If a Gemini API key is set it is used; otherwise the director obtains a bearer token through Application Default Credentials as the Cloud Run service account. If neither works it marks itself off for the life of the process: one failed lookup, not one per attack. There is no key to create, store, rotate, or leak, and the two secrets the app does need live in Secret Manager.
  2. The one IAM surprise. The Gemini API defines no IAM permissions of its own, so the service account needs the Service Usage consumer role, which is the only gate there is to pass. And the key type matters if you do use one: as of September 2026 the API accepts only keys bound to a service account, not the older unrestricted ones.
  3. Low thinking, short timeouts. Every pass runs with thinking set low, because this is a short, well-specified writing task with a fixed output shape, and the point is that it finishes while the player is still taking their turn. Directions time out at twenty seconds, staging at twelve because it is on the path to the clip, and a timeout is a null, never a wait.
  4. A six-slot semaphore. All four pass types share one small in-process semaphore, so a full bench does not open ten Gemini calls at once.
  5. Optimistic by design. Application Default Credentials cannot be checked synchronously, so the director reports itself as configured until proven otherwise. Everything downstream already treats a null direction as normal, so an optimistic yes costs one lookup rather than a wrong answer.

The director is the part of the game I would most want another engineer to read, because it is a worked example of using a language model for a narrow, cacheable, fully optional job with a deterministic fallback, on Google Cloud, with the credentials handled the way the platform wants. The broader architecture, including how the same engine runs on the server for online play, is in the Cloud Run architecture article. Start with stagingKey: the key design is the design.

Book a 30-min callEmail about this work