Migrate from Gemini 3.8 Flash to Hydrogen Without Losing Context

Move Gemini 3.8 Flash requests to Hydrogen with explicit thinking settings, restored cache contents, preserved tool history and a regression and rollback plan.

A flat railway turnout with an orange switch blade, illustrating a route change that preserves the connection.

To migrate from Gemini 3.8 Flash to Gemini 4 Hydrogen, preserve your API contract and application context, change the model ID, choose the thinking level explicitly, and rerun task-level checks before routing production work. A model-name replacement alone does not restore documents behind an unsupported cache reference or prove that an existing server-held conversation can continue across models.

This guide covers an existing working application, rather than obtaining a first key. For that first request, start with the Hydrogen API setup guide. Here we build a small before-and-after request, inspect history preservation, and define acceptance and rollback for a real migration. “Without losing context” describes the checks and reconstruction you must perform; it is not a guarantee that the two models produce identical answers.

Documentation was checked on November 14, 2026. Our downloadable kit passed 21 offline request-audit tests and a separate check of actual google-genai==3.3.0 request serialization using a mock HTTP transport. We did not call either model, validate a real cross-model conversation, measure quality or compare bills. The regression criteria below are proposed checks for your application, not reported benchmark results.

Identify what actually changes

Read the Hydrogen migration guidance alongside the Gemini 3.8 release documentation. Otherwise, restrictions repeated in a new checklist can look like new breaking changes.

AreaExisting Gemini 3.8 Flash behaviorHydrogen migration decision
Model ID on Googlegemini-3.8-flashUse gemini-4-hydrogen; independently confirm access on the intended account
Default thinkingmediumDefault becomes high; set an explicit level for a controlled comparison
Thinking choiceslow, medium, highAdds xhigh; minimal was already unsupported on 3.8
Context budgetingInput and output limits are separateInput, thinking and output share a 1,048,576-token window
Explicit context cachingAudit whether the existing request depends on a cache resourceHydrogen does not support explicit caching; reconstruct the context before removing the reference
Sampling controlsAlready deprecated in the 3.8 migration guidanceHydrogen ignores in-range custom values; out-of-range values can still return a 400 validation error
Longer outputExisting application may assume one responseAbove the 65,536-token synchronous per-hop limit, design background execution or client continuation

Setting Hydrogen to medium controls one configuration variable; it does not establish equivalent internal reasoning, latency or answer quality. Similarly, a larger advertised output ceiling does not mean a near-full input leaves that much output space. Budget against the shared window, including thinking, and keep an application-level output and spending limit.

English Google documentation showing the Gemini 3.8 Flash migration checklist and its context, thinking, caching and sampling notes.

Actual screenshot of Google’s English migration documentation. It records the source guidance, not a successful API migration or an Ofox performance test.

For the output mechanics, use Google’s long-decode documentation. A per-hop limit is a controller-design boundary, not evidence that every larger requested output cap is intrinsically invalid.

Freeze the source configuration and keep the same protocol

Before changing a model, save a versioned source configuration and a small reproducible task set. Record the model, endpoint, SDK version, system instructions, input construction, tools, response schema, output cap, storage settings, retry policy and any provider routing fields. Keep the original source documents and permitted user inputs in your normal protected storage; a public debug log is not a migration archive.

There are three different request shapes to distinguish:

Existing callerPreserve this boundaryDo not paste into it
Google Interactionsinput, generation_config, interaction steps and IDsA GenerateContent contents envelope
Google GenerateContentcontents, content parts, tool declarations and SDK configurationInteractions previous_interaction_id as a substitute for its history
Ofox OpenAI-compatible callerIts documented messages, model routing and response contractGoogle’s native Interactions request unchanged

The complete fixture below uses Google Interactions. The kit’s separate serialization test uses GenerateContent because it checks preservation of model parts and tool responses. They are deliberately separate tests; running one does not convert the other protocol.

For an Ofox application, first check the exact route you already use: Gemini Generate Content or OpenAI-compatible Chat Completions. Use the corresponding Ofox key and authentication instructions. A Google key and an Ofox key are not interchangeable. Ofox’s documentation of a Gemini-native route does not establish support for every Google Interactions feature or model-specific cache capability.

Keep tool-client migrations separate from application migrations. If Cline or OpenCode constructs the request for you, follow the Hydrogen coding-tool configuration guide and inspect that client’s actual output rather than assuming it sends the JSON shown here.

Make a small, explicit before-and-after request

Use a task whose correct result you can check without asking another model. The source fixture contains two record statuses; only record B is blocked. Save this complete object as source-request.json:

{
  "model": "gemini-3.8-flash",
  "input": "Records: A=ready; B=blocked. Return the blocked record IDs only.",
  "generation_config": {
    "max_output_tokens": 8192
  },
  "response_format": {
    "type": "text",
    "mime_type": "application/json",
    "schema": {
      "type": "object",
      "properties": {
        "blocked_ids": {"type": "array", "items": {"type": "string"}}
      },
      "required": ["blocked_ids"],
      "additionalProperties": false
    }
  }
}

Create hydrogen-request.json by preserving the input, schema and output cap while changing the model and making thinking explicit:

import json
from pathlib import Path

source = json.loads(Path("source-request.json").read_text())
target = json.loads(json.dumps(source))
target["model"] = "gemini-4-hydrogen"
target["generation_config"]["thinking_level"] = "medium"
Path("hydrogen-request.json").write_text(json.dumps(target, indent=2))

Both complete JSON files are included in the kit. The 8,192-token cap is a controlled fixture setting, not a universal production recommendation. Even a small final JSON answer can fail if thinking exhausts the available budget. Check completion and truncation; do not automatically raise a production cap to the maximum to hide a failure.

The response format follows Google’s current structured-output contract: text output with an application/json MIME type and a schema. The schema restricts the shape, but it does not prove that the model chose the correct record.

After configuring your own Google project key in GEMINI_API_KEY, you can run the following optional live request. This command contacts Google and can consume project allowance or paid usage; we did not execute it for this article.

curl --fail-with-body --max-time 180 \
  'https://generativelanguage.googleapis.com/v1beta/interactions' \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @hydrogen-request.json \
  --output hydrogen-response.json

Run the same command with source-request.json and a separate output filename for your source baseline. Keep the account, input, schema and execution conditions comparable. First inspect the interaction status and any error or incomplete result. Only a completed response containing the expected output should reach your application parser. Parse the JSON text and require exactly {"blocked_ids":["B"]} for this fixture, with no additional keys or IDs. An HTTP 200, a valid JSON document and a correct task answer are three different checks.

If the request times out, retain available request or interaction identifiers and inspect service state before retrying. A client timeout alone does not prove that the server stopped working.

Run the offline migration kit and understand its limits

Download the Hydrogen migration kit, extract it, and enter the hydrogen-migration-kit directory. Use Python 3.11 or newer for the combined tooling. The request auditor needs only the standard library:

python -m unittest test_audit.py -v
python migration_audit.py source-request.json
python migration_audit.py hydrogen-request.json

The expected unit-test result is 21 tests passed. The auditor does not rewrite the request file. It returns an unchanged copy with blocker and review findings. Exit code 2 means blockers were found; exit code 0 means this scoped audit found no blocker, not that deployment is approved. For example, the target fixture still requires application evaluation and review of its deliberately limited output cap.

The auditor checks complete initial Interactions requests. It flags unsupported protocol envelopes, missing input, explicit cache dependencies, invalid thinking choices, malformed output limits and incompatible storage/background settings. It also highlights changes hidden by defaults. It cannot recover cached documents, inspect server-held history, establish account permissions or validate every field accepted by the service.

Its output includes the complete copied request. Use the supplied non-sensitive fixture first; avoid sending confidential prompts to shared terminal logs. API keys do not belong in the request JSON.

For the separate SDK serialization check, create an isolated environment:

python -m venv .venv
source .venv/bin/activate
python -m pip install 'google-genai==3.3.0' httpx
python sdk_wire_check.py

On Windows PowerShell, activate with .venv\Scripts\Activate.ps1. Package installation downloads dependencies; the check itself uses an explicitly synthetic key and httpx.MockTransport, reads no environment credentials and makes no model request.

The script serializes two GenerateContent requests through the installed SDK. It asserts that both preserve the same three history turns, tool declarations and two tool responses. The model turn contains two parallel function calls; a synthetic signature stays on its original first part and is not copied onto the second. The target request sets Hydrogen and explicit MEDIUM thinking. Inspect sdk-wire-requests.json beside the script for the captured bodies.

That is evidence about local serialization. The synthetic response and signature do not establish server acceptance, valid cross-model continuation or a working tool executor. A passing offline check is useful because it catches accidental history loss before a live evaluation; it cannot replace that evaluation.

Restore cached content and preserve conversation state

An explicit cache identifier is a reference, not the document itself. Removing cached_content or cachedContent can make a request appear simpler while silently discarding the material the application depended on. Google’s caching documentation distinguishes implicit reuse from explicitly managed cache resources; implicit caching cannot reconstruct missing input for you.

For each existing cache-dependent task, perform this reconstruction:

  1. Locate the original caller-owned system instructions, documents, media references and tool declarations used to create the cache. If you cannot recover them, stop that migration case instead of treating an empty replacement as equivalent.
  2. Record their versions and ordering. Check that external file references remain accessible to the target account and request path.
  3. Rebuild a complete request using fields appropriate to your current protocol. Preserve the system/user distinction and the tools; do not flatten everything into a user message merely to remove the cache ID.
  4. Recount the reconstructed context against Hydrogen’s shared budget, including room for thinking and the answer. Partition the task if necessary.
  5. Ask a fixture question that depends on a known fact in the restored material. Verify its exact answer before removing the old cache-dependent path from service.

Conversation state needs a separate decision. In Interactions, a stored previous interaction can be referenced through previous_interaction_id. Using store=false for the current request does not by itself prevent reading previously stored state, but the new result is not stored for a later continuation. Combining background execution with store=false is incompatible. Do not infer cross-model continuation support from the mere existence of a previous ID; test the intended account and model combination or start a fresh, explicitly reconstructed canary conversation.

For stateless continuation, retain the complete required sequence, including thought-related steps and built-in tool signatures specified by the API. For GenerateContent, preserve complete model content and its parts in order, followed by the corresponding tool responses. A renderer’s visible text transcript is not a sufficient history store.

If a request reports a missing thought signature, use the Gemini tool-call signature troubleshooting guide and the official signature rules. Keep each signature on its original part. Do not duplicate one signature across parallel function calls or invent a replacement. The kit’s synthetic signature exists only to catch serializer mistakes offline.

Check tools, output and the shared budget together

A migrated request can preserve all its text and still lose application behavior. Keep function names, argument schemas, permissions, call/result associations and result ordering consistent. Google’s function-calling guide describes the protocol; your executor must still decide which proposed operations are allowed and whether each actually succeeded.

Use a read-only fixture before any write-capable tool. For example, have lookup_record return A as ready and B as blocked, then require the final structured answer to identify B. Log call IDs, argument values and tool results without logging secrets. If the model emits two calls, return both corresponding results; do not collapse them into a single unstructured summary that loses their association.

Treat model output as proposed application data. For the record fixture, validate the schema, then validate the answer against the known records. For a write operation, inspect the actual destination state. “Saved successfully” in model text is not proof of a write. If using UI execution rather than function tools, the Computer Use setup guide covers the additional observe, approve, execute and verify loop.

Budget failures can resemble task failures. Capture input usage, output usage, reported thinking usage where available, completion state and truncation indicators. Keep absent usage as unknown, not zero. Do not add a thinking figure a second time if the provider’s output total already includes it. Use the provider’s documented units before deriving costs.

For a long answer, explicitly choose the continuation controller or background path and its stopping conditions. Preserve the resume identifier, avoid replaying completed side effects, and cap total task work across hops. Increasing a single request limit without changing the controller does not create a reliable long-running task.

Build a regression set with independent acceptance criteria

Start from real application cases, stripped of secrets and used with appropriate access. Include successful cases and known failure boundaries. The table below is a reproducible design for a small suite; it contains no measured model results.

CaseConcrete fixturePass criterion
Basic extractionA=ready; B=blockedCompleted response parses to exactly the blocked ID B
Restored cacheA source document states release_owner=team_amber; the question omits that factAnswer is team_amber only after the complete document is restored
History continuityFirst turn assigns record A to team_amber; next asks who owns ACorrect owner is returned through the application’s chosen state mechanism
Parallel toolsTwo lookup_record calls for A and BBoth results retain their associations; no duplicate execution; final answer matches the fixtures
Controlled truncationA deliberately insufficient output cap on a larger fixtureApplication detects incomplete output and withholds acceptance
Invalid configurationAn out-of-range sampling value or incompatible background/storage combinationError reaches the correct handling path, rather than an unconditional retry loop
Rollback with writesA test operation has a recorded operation ID and uncertain client responseOperator or executor checks destination state before any replay

For each run, save the configuration version, model ID, prompt/fixture hash, SDK version, account or routing environment, start/end time, completion state, validator result and available usage. Store sensitive raw responses only under your normal retention policy. Compare like-for-like cases; do not attribute an improvement to the model if you also changed the prompt, schema and executor.

Define acceptance before running the paid or allowance-consuming evaluation. Schema validity and side-effect safety can have strict requirements. Task accuracy, latency and cost need thresholds appropriate to the application and a meaningful sample. This article does not supply a universal percentage or pretend that seven fixtures establish production reliability. Inspect disagreements individually, especially plausible answers that fail a deterministic check.

Roll out gradually and retain a usable rollback

First route a bounded set of new, read-only tasks to the Hydrogen configuration. Keep source and target configurations separately selectable, with the same approved fixture versions. Review failures and incomplete responses before widening the canary. Add write-capable tasks only after their executor, deduplication and destination-state checks have passed.

For malformed requests, fix the request instead of retrying identical input. For missing model access, verify the exact account, route and model ID. For transient failures, apply bounded retries with backoff and preserve identifiers. Ofox callers should follow the documented error and retry behavior. The existing Gemini 4 API error diagnosis article is also useful for separating access, request-format and rate-limit failures, although its model-specific examples use Argon and must not be copied as Hydrogen IDs.

Rollback means restoring the source configuration for eligible new tasks, not blindly replaying every in-flight interaction. Pause new side effects, identify uncertain operations, inspect their destination state, and then decide whether to resume, compensate or restart. Keep the old route available only for as long as its access and model availability remain valid; a saved configuration cannot override provider retirement or lost account permissions.

The migration is ready when the application can demonstrate restored context, preserved tool state, correctly validated outputs, bounded execution and a rehearsed rollback on its actual route. Retain the versioned evidence so a later prompt, SDK or provider change can be distinguished from this model migration.