
Gemini 4 Argon Long Decode: 200K Tokens, One Request
Summary
Use Argon's background long decode to generate 1M tokens of output, with cost math.
Until this week, every Gemini call had a ceiling: about 64K tokens of output. If you wanted a full migration runbook, a book-length report, or a codebase-wide refactor plan, you chunked the work by hand and stitched it back together. On October 13, 2026 Google made Gemini 4 Argon broadly available, and the part developers are passing around is long decode: one request that can generate up to 1,048,576 tokens, with the server doing the stitching for you.
This guide shows how to use it from Python through the Interactions API: start a background run, poll it safely, extract the text, and (the part most posts skip) predict what it will cost before you press go. The cost model matters because every 64K segment of output re-bills everything that came before it. By the end you will have a small, tested module you can drop into a project.
A note on what was verified. The parameter names, statuses and limits below come from Google's Gemini API docs for gemini-4-argon and its long decode page. I ran the module against a fake client to check the logic and confirmed the SDK method signatures, but I did not run a live 200K-token generation, so the numbers in the example output are from the test harness and the arithmetic, not from a real Argon bill. Check your own usage object on the first run.
What long decode actually is
Argon has a 1M-token window shared by input, thinking and output. A normal synchronous call is still capped at 65,536 output tokens. Long decode lifts that cap by running the generation in the background: the server produces output in 64K hops, each hop is recorded as a model_output step under the same interaction ID, and you join the text from all steps. A run can last up to 24 hours.
| Setting | Output limit |
|---|---|
| background: false | 65,536 (higher values return HTTP 400) |
| background: true, no max_output_tokens | 65,536 |
| background: true, max_output_tokens above 65,536 | Your value, up to 1,048,576 minus input tokens |
Google also documents a client-side continuation path on the GenerateContent API (64K per stream, 20-minute run time, nothing stored server-side). This guide uses the Interactions route because it is the one the docs call supported for long decode, and the client-side path is noted as coming to Interactions later.
Prerequisites
- Python 3.10+ and a Gemini API key in
GEMINI_API_KEY(paid tier). - The
google-genaipackage, version 2.3.0 or later:pip install -U google-genai. - Comfort with polling a job. There is no long-lived connection to babysit in this approach.
Step 1: Know the bill before you start
Here is the gotcha that will surprise you. The usage object reports total_input_tokens as the sum of the input of every hop. Hop 1 reads your prompt. Hop 2 reads your prompt plus the 64K it just wrote. Hop 3 reads the prompt plus 128K, and so on. Input grows linearly per hop, so the billed total grows quadratically with output length.
Google's own example: a 1,000-token prompt that produces 200,000 output and thinking tokens reports 397,216 input tokens, while the real context is about 201,000. You can reproduce that number exactly. With 4 hops, billed input is 4 × 1,000 + 65,536 × (0 + 1 + 2 + 3) = 397,216. That formula is the heart of the cost estimator below.
Pricing during the introductory period (through November 30, 2026) is $2 per million input tokens, $10 per million output tokens, and $0.10 for cached input. From December 1 it moves to $4 and $20. Implicit caching gives a 95% discount on repeated hop input, but treat that as a bonus, not a plan: the estimator below assumes no cache hits unless you tell it otherwise. I also assume thinking tokens bill at the output rate, which is how earlier Gemini models worked; confirm against your first invoice.
Step 2: The module
Save this as longdecode.py. It has five jobs: estimate worst-case cost, start a background interaction, poll it, pull out the text, and compute the true context size.
import math, time
from google import genai
client = genai.Client() # reads GEMINI_API_KEY
MODEL = "gemini-4-argon"
HOP = 65_536 # server generates output in 64K hops
PRICE = { # USD per 1M tokens: (input, output, cached input)
"intro": (2.00, 10.00, 0.10), # through Nov 30, 2026
"standard": (4.00, 20.00, None), # from Dec 1, 2026 (cached rate not published)
}
TERMINAL = {"completed", "incomplete", "failed", "cancelled", "requires_action"}
def worst_case_cost(prompt_tokens, max_out, plan="intro", cache_hit=0.0):
"""Upper-bound spend. Every hop re-bills the whole context so far."""
hops = math.ceil(max_out / HOP)
billed_in = sum(prompt_tokens + k * HOP for k in range(hops))
p_in, p_out, p_cached = PRICE[plan]
cached = billed_in * cache_hit if p_cached is not None else 0
cost = ((billed_in - cached) * p_in + cached * p_cached + max_out * p_out) / 1e6
return {"hops": hops, "billed_input": billed_in, "usd": round(cost, 2)}
def start(prompt, max_out, level="high"):
it = client.interactions.create(
model=MODEL,
input=prompt,
background=True, # required for long decode
store=True, # background needs stored interactions
generation_config={"max_output_tokens": max_out, "thinking_level": level},
)
return it.id
def wait(iid, every=20, deadline_s=6 * 3600):
t0 = time.time()
while True:
it = client.interactions.get(id=iid)
if it.status in TERMINAL:
return it
if time.time() - t0 > deadline_s:
client.interactions.cancel(id=iid) # you still pay for work done
raise TimeoutError(f"cancelled {iid} after {deadline_s}s")
time.sleep(every)
def text_of(it):
out = []
for step in it.steps:
if step.type == "model_output":
out += [c.text for c in step.content if c.type == "text"]
return "".join(out)
def context_size(prompt_tokens, usage):
# NOT usage.total_input_tokens: that sums every hop's input.
return prompt_tokens + usage.total_output_tokens + usage.total_thought_tokens
def long_decode(prompt, prompt_tokens, max_out=200_000, level="high", budget_usd=5.0):
est = worst_case_cost(prompt_tokens, max_out)
if est["usd"] > budget_usd:
raise RuntimeError(f"worst case ${est['usd']} exceeds budget ${budget_usd}: {est}")
iid = start(prompt, max_out, level)
print("started", iid, est)
it = wait(iid)
if it.status == "incomplete":
print("hit max_output_tokens; thinking may have eaten the budget")
if it.status in ("failed", "cancelled"):
raise RuntimeError(f"{iid} ended {it.status}")
return iid, it.status, text_of(it), it.usage
Three design choices are worth explaining. First, long_decode refuses to start if the worst-case estimate is over your budget, which is cheap insurance against a typo turning 200000 into 2000000. Second, wait cancels on timeout, because a forgotten background run keeps billing. Third, context_size follows the docs' advice: use prompt plus output plus thought tokens, never total_input_tokens, when deciding whether you are near the window.
Step 3: See the numbers
Run the estimator before any real call. These come straight from the module for a 1,000-token prompt:
>>> worst_case_cost(1000, 200_000)
{'hops': 4, 'billed_input': 397216, 'usd': 2.79}
>>> worst_case_cost(1000, 200_000, cache_hit=0.9)
{'hops': 4, 'billed_input': 397216, 'usd': 2.12}
>>> worst_case_cost(1000, 1_047_576)
{'hops': 16, 'billed_input': 7880320, 'usd': 25.76}
Notice the shape. Going from 200K to roughly 1M output (5x the text) takes you from $2.79 to $25.76 (9x the cost), because billed input balloons from about 0.4M tokens to 7.9M. Output itself is still the bigger line at the low end ($2.00 of the $2.79), but at the top of the range input is about $15.76 of the $25.76 before any caching. After December 1 both rates double.
The estimate is a ceiling for the case where the model uses every token you allowed. Thinking tokens count against max_output_tokens too, so a high thinking level on a hard prompt can burn a large share of the budget before a word of visible text appears.
Step 4: A worked example, a 150-page migration runbook
Suppose you are moving a payments service off an old queue and want one document that covers every phase: inventory, dual-write, cutover, rollback, and a per-team checklist. That is genuinely long-form work where one coherent pass beats stitched chunks, because the rollback section needs to reference decisions made in the inventory section.
from longdecode import long_decode
PROMPT = """You are a staff engineer writing a migration runbook.
Service: payments-core, moving from RabbitMQ to a managed Kafka cluster.
Write ONE continuous runbook with these parts, numbered, each with
sub-steps, owners, verification commands and rollback criteria:
1 Inventory 2 Dual-write 3 Shadow-read 4 Cutover 5 Rollback
6 Per-team checklists (payments, risk, support, data)
Be exhaustive. Do not summarize earlier parts; reference them by number."""
iid, status, text, usage = long_decode(
PROMPT, prompt_tokens=180, max_out=200_000, level="medium", budget_usd=5.0
)
open("runbook.md", "w").write(text)
print(status, usage.total_output_tokens, usage.total_thought_tokens)
The run returns an interaction ID immediately and the job continues server-side. Here is what the harness printed when I ran this path against a fake client (the interaction ID and counts are placeholders, only the shape is real):
create kwargs: {'model': 'gemini-4-argon', 'background': True, 'store': True,
'generation_config': {'max_output_tokens': 200000, 'thinking_level': 'medium'}}
started int_demo {'hops': 4, 'billed_input': 393936, 'usd': 2.79}
completed 150000 50000
In a real run, expect the first 64K tokens to take roughly ten minutes, after which output arrives in chunks of around 5,000 tokens. Long pauses between chunks are normal, so do not treat silence as failure. A 20-second poll interval is plenty.
Why medium thinking here? Argon defaults to medium, and the docs reserve high for the hardest tasks. A runbook is long but not deeply puzzling. Spending the budget on visible output instead of reasoning is the better trade.
Step 5: Handle every status
Do not assume completed. The interaction can end in five different ways and each wants a different response:
| Status | Meaning | What to do |
|---|---|---|
| in_progress / queued | Still running | Keep polling |
| completed | Model finished | Read the text |
| incomplete | max_output_tokens ran out | Raise the cap or lower thinking_level; text may be empty |
| requires_action | Model requested a tool call | Send the tool result using the interaction ID |
| failed | Server error, or run exceeded 24 hours | Retry from a smaller task; you pay for work done |
| cancelled | You cancelled it | Check usage for billed tokens |
To continue a finished conversation, pass previous_interaction_id. Remember that tools, system_instruction and generation_config apply only to the current interaction, so set them again each turn.
Common pitfalls
- Output stops at 64K. Either
backgroundis false ormax_output_tokensis unset. Both need to be set. Setting a high value without background returns a 400. - Empty text with status incomplete. Thinking consumed the whole budget. Raise the cap or drop to a lower
thinking_level. - Using total_input_tokens to decide when to compact. It overstates your context by a lot. Use prompt + output + thought tokens.
- store=false. Background runs need stored interactions. The two options are incompatible.
- Low output caps in your framework. Agent frameworks and eval harnesses that clamp output at something like 8,192 will cut Argon off mid-thought. Check any wrapper config.
- Asking for a length. The docs say the model ignores requested word or token counts. Control length with structure (numbered parts, required sections) and
max_output_tokens, not with 'write 50,000 words'. - Using it for chat or short tool loops. Long decode is wrong for latency-sensitive work and for prompts close to the input limit.
- Forgetting the promo ends. Cost scripts hard-coded to $2 and $10 will under-report from December 1. Keep the price table in one place, as the module does.
- Not cancelling. A background job you abandon still runs and still bills. Always keep the ID, and cancel on timeout.
Quick reference
| Item | Value |
|---|---|
| Model ID | gemini-4-argon |
| Default output cap | 65,536 |
| Long decode cap | 1,048,576 minus input tokens |
| Required flags | background=True, store=True |
| Thinking levels | low, medium (default), high |
| Hop size | ~64K output tokens |
| Max run time | 24 hours |
| Poll | client.interactions.get(id=...) |
| Cancel | client.interactions.cancel(id=...) |
| Text location | steps where type == 'model_output', content type 'text' |
| True context | prompt + total_output_tokens + total_thought_tokens |
| Intro pricing (to Nov 30) | $2 in / $10 out / $0.10 cached |
| Standard pricing (Dec 1+) | $4 in / $20 out |
Next steps
- Wire
worst_case_costinto CI or a pre-flight check so nobody launches a $25 job by accident. - Add streaming with
last_event_idreconnects if you want live progress; read the stream to the end before checking status. - Combine it with structured outputs or file search for documents that must cite your own sources.
- Compare against the Batch API and Flex inference, which Argon also supports, if the job is not time-sensitive.
Sources: Gemini API long decode docs, Gemini 4 Argon model page, Interactions API docs, VentureBeat on general availability and pricing.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.