Skip to content
Gemini 4 Orchestrator: Carbon Plans, Hydrogen Ships Code — ContentBuffer guide

Gemini 4 Orchestrator: Carbon Plans, Hydrogen Ships Code

K
Kodetra Technologies··12 min read Intermediate

Summary

Rebuild Antigravity's Carbon-plans, Hydrogen-builds loop in Python with tests and a cost meter.

Google shipped Gemini 4 Hydrogen on November 12, two days after opening Gemini 4 Carbon to paying developers. The Hydrogen launch thread hit the top of Hacker News with hundreds of comments, and half of them were arguing about the same thing: where does Hydrogen sit relative to Carbon and Argon, and which one should you actually call?

Google's own answer is hiding inside Antigravity. Its new Orchestrator option doesn't pick one model. Carbon starts every task in a read-only planning phase, Hydrogen does the edits and runs the tests, and control goes back to Carbon when Hydrogen hits friction, such as a verification step that fails twice. Google says this lands near Carbon-level task success while using 24% less quota and finishing 19% faster (self-reported, on Terminal-Bench).

Antigravity's Orchestrator is a fixed product setting. You can't tune it, and you can't use it from your own backend. In this guide you'll rebuild the same pattern with the public Interactions API in about 200 lines of Python: Carbon writes a structured plan, Hydrogen implements one function per step, a local test runner verifies every step for real, two failures trigger a Carbon re-plan, and a cost meter tells you what each role spent.

What you'll build

  • A planner call to gemini-4-carbon that returns a typed JSON plan (pydantic schema via response_format).
  • An executor call to gemini-4-hydrogen that writes one function per step, at medium thinking first and high on retry.
  • A verifier that runs the plan's own assert lines in an isolated subprocess, so "done" means the tests passed, not that the model said so.
  • An escalation rule copied from Antigravity: two failed checks on a step hand it back to Carbon for a re-plan.
  • A per-call cost meter built on interaction.usage, priced with the official launch rates.

Prerequisites

  • Python 3.10+ and pip install -U "google-genai>=2.3.0" pydantic. The Interactions API needs google-genai 2.3.0 or newer.
  • A Gemini API key from AI Studio in GEMINI_API_KEY. Hydrogen works on the free tier (rate-limited). Carbon is paid-tier only, so you need billing enabled for the planner.
  • Comfort reading JSON Schema and pydantic models.

The two models in one table

These numbers come from Google's official what's-new pages for each model. Note the Carbon price change on December 1.

gemini-4-carbongemini-4-hydrogen
Role herePlanner, re-plannerExecutor
Input / 1M tokens$2.00 (from Dec 1: $4.00)$1.50
Output + thinking / 1M$10.00 (from Dec 1: $20.00)$7.50
Thinking levelslow, medium (default), highlow, medium, high (default), xhigh
Context1,048,576 shared in+out1,048,576 shared in+out
Sync output cap65,536 per hop65,536 per hop
Free tierNoYes, rate-limited

Step 1: Make one Interactions call to each model

Google now treats the Interactions API (client.interactions.create) as the default and calls generateContent legacy. Thinking goes in generation_config, and the text comes back on output_text. Smoke-test both models before building anything:

from google import genai

client = genai.Client()  # reads GEMINI_API_KEY

for model, level in [("gemini-4-carbon", "medium"), ("gemini-4-hydrogen", "low")]:
    it = client.interactions.create(
        model=model,
        input="In one sentence: what does a planner model do in an agent?",
        generation_config={"thinking_level": level},
    )
    u = it.usage
    print(model, "|", it.output_text.strip())
    print("  in", u.total_input_tokens, "out", u.total_output_tokens,
          "thought", u.total_thought_tokens)

You'll get one sentence per model plus four usage numbers. The one to watch is total_thought_tokens, because you pay for thinking at the output rate even though you never see it. On Hydrogen the default is high, so a lazy call with no generation_config buys you the most expensive non-xhigh reasoning on every request.

Step 2: Set up the module, prices and the plan schema

Create orchestrator.py. The header pins both model IDs and the launch prices in one place so the meter and any later price change stay in sync:

import json
import subprocess
import sys
import tempfile
import textwrap
from dataclasses import dataclass, field

from pydantic import BaseModel

PLANNER = "gemini-4-carbon"
EXECUTOR = "gemini-4-hydrogen"

# USD per 1M tokens. Output price covers thinking tokens.
# Carbon intro pricing runs through Nov 30, 2026, then $4 / $20.
PRICES = {
    PLANNER: {"in": 2.00, "out": 10.00},
    EXECUTOR: {"in": 1.50, "out": 7.50},
}

The plan is the contract between the two models, so make it a real schema. Every step names the exact function to write and carries its own asserts. That last field is the important design choice: the planner defines what "done" means, and the executor never gets to grade its own homework.

# ---------- structured plan ----------
class Step(BaseModel):
    id: int
    title: str
    instruction: str
    function_name: str
    tests: str  # plain assert statements that must pass


class Plan(BaseModel):
    goal: str
    assumptions: list[str]
    steps: list[Step]

Step 3: Meter every call

The meter reads usage straight off each interaction and prices output and thinking together, which matches how Google bills both models:

# ---------- cost meter ----------
@dataclass
class Meter:
    rows: list = field(default_factory=list)

    def add(self, role, model, interaction):
        u = interaction.usage
        inp = u.total_input_tokens or 0
        out = (u.total_output_tokens or 0) + (u.total_thought_tokens or 0)
        p = PRICES[model]
        cost = inp / 1e6 * p["in"] + out / 1e6 * p["out"]
        self.rows.append((role, model, inp, out, cost))
        return cost

    def report(self):
        total = 0.0
        for role, model, inp, out, cost in self.rows:
            total += cost
            print(f"{role:<10} {model:<18} in={inp:>6} out+think={out:>6} ${cost:.4f}")
        print(f"{'TOTAL':<29}{'':>28} ${total:.4f}")
        return total

Step 4: The planner, executor and re-planner calls

Structured output in the Interactions API is a top-level response_format argument with type, mime_type and a JSON Schema under schema. That's different from the generateContent shape, so don't copy older snippets. Carbon uses it for both the plan and the re-plan. Hydrogen just returns raw code.

# ---------- model calls ----------
PLAN_PROMPT = """You are the planner. Do not write the implementation.
Break the task into 2-5 small Python functions that can each be tested alone.
For every step give: a precise instruction, the exact function_name, and
3-6 plain `assert` lines that call that function and pin down edge cases.
Later steps may call functions from earlier steps.

TASK:
{task}
"""

BUILD_PROMPT = """Implement exactly one Python function.
Return ONLY code: no prose, no markdown fences.
Use the standard library only. Earlier functions already exist in scope.

Function name: {name}
Instruction: {instruction}
These asserts must pass:
{tests}
{feedback}"""

REPLAN_PROMPT = """The executor failed this step twice.
Step: {step}
Last error:
{error}
Rewrite ONLY this step so it is achievable: clarify the instruction, and fix
any assert that contradicts the instruction. Keep the same function_name."""


def make_plan(client, task, meter):
    it = client.interactions.create(
        model=PLANNER,
        input=PLAN_PROMPT.format(task=task),
        generation_config={"thinking_level": "medium"},
        response_format={
            "type": "text",
            "mime_type": "application/json",
            "schema": Plan.model_json_schema(),
        },
    )
    meter.add("plan", PLANNER, it)
    return Plan.model_validate_json(it.output_text)


def replan_step(client, step, error, meter):
    it = client.interactions.create(
        model=PLANNER,
        input=REPLAN_PROMPT.format(step=step.model_dump_json(), error=error[-1500:]),
        generation_config={"thinking_level": "high"},
        response_format={
            "type": "text",
            "mime_type": "application/json",
            "schema": Step.model_json_schema(),
        },
    )
    meter.add("replan", PLANNER, it)
    return Step.model_validate_json(it.output_text)


def strip_fences(code):
    code = code.strip()
    if code.startswith("```"):
        code = code.split("\n", 1)[1]
        code = code.rsplit("```", 1)[0]
    return code.strip() + "\n"


def build_step(client, step, feedback, meter, level="medium"):
    it = client.interactions.create(
        model=EXECUTOR,
        input=BUILD_PROMPT.format(
            name=step.function_name,
            instruction=step.instruction,
            tests=step.tests,
            feedback=f"\nYour previous attempt failed with:\n{feedback}" if feedback else "",
        ),
        generation_config={"thinking_level": level},
    )
    meter.add("build", EXECUTOR, it)
    return strip_fences(it.output_text)

Three things in there are deliberate. The planner prompt says "do not write the implementation", because Antigravity's planning phase is read-only and a planner that starts coding burns the expensive tokens you were trying to save. The re-planner runs at high, since by then something is wrong with the spec, not with the typing. And strip_fences exists because models still add Markdown fences sometimes even when told not to.

Step 5: Verify by actually running the tests

This is the part most "planner/executor" demos skip. The verifier stitches all previously passing functions, the new function and the step's asserts into one file, then runs it with python -I in a subprocess with a timeout. Exit code zero plus a printed OK is the only thing that counts as a pass.

# ---------- verifier: run the asserts for real ----------
def verify(prior_code, new_code, tests, timeout=20):
    src = prior_code + "\n" + new_code + "\n" + textwrap.dedent(tests) + "\nprint('OK')\n"
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
        f.write(src)
        path = f.name
    try:
        r = subprocess.run([sys.executable, "-I", path], capture_output=True,
                           text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        return False, "timeout"
    ok = r.returncode == 0 and r.stdout.strip().endswith("OK")
    return ok, (r.stderr or r.stdout)[-2000:]

A subprocess is isolation from your process, not a sandbox. It stops a bad function from crashing the orchestrator, but the generated code can still touch your filesystem. Run this in a container or throwaway VM if the task involves anything you didn't write yourself.

Step 6: The orchestration loop

Now wire it together. Each step gets two Hydrogen attempts (medium, then high with the test failure as feedback). If both fail, Carbon rewrites that one step and Hydrogen tries again. One re-plan per step is the ceiling, after which the run fails loudly instead of looping forever.

# ---------- the loop ----------
def orchestrate(client, task, max_tries=2, max_replans=1):
    meter = Meter()
    plan = make_plan(client, task, meter)
    print(f"PLAN: {plan.goal}")
    for s in plan.steps:
        print(f"  {s.id}. {s.title} -> {s.function_name}()")

    module = ""
    for step in plan.steps:
        replans = 0
        while True:
            feedback = None
            for attempt in range(1, max_tries + 1):
                level = "medium" if attempt == 1 else "high"
                code = build_step(client, step, feedback, meter, level)
                ok, log = verify(module, code, step.tests)
                print(f"[step {step.id}] attempt {attempt} ({level}): {'PASS' if ok else 'FAIL'}")
                if ok:
                    module += "\n" + code
                    break
                feedback = log
            if ok:
                break
            if replans >= max_replans:
                raise RuntimeError(f"step {step.id} failed after re-plan:\n{feedback}")
            print(f"[step {step.id}] handing back to {PLANNER}")
            step = replan_step(client, step, feedback, meter)
            replans += 1

    meter.report()
    return module


if __name__ == "__main__":
    from google import genai

    TASK = """Write a small library that turns messy invoice lines like
    'INV-0042 | 3 x Widget @ $4.50 | 2026-11-03' or 'inv 43;1x Gadget;12,00 EUR;03/11/2026'
    into dicts {invoice, qty, item, unit_price, currency, date (ISO)}.
    Default currency USD. Reject lines with no invoice number by raising ValueError."""

    client = genai.Client()  # reads GEMINI_API_KEY
    code = orchestrate(client, TASK)
    open("invoice_parser.py", "w").write(code)
    print("wrote invoice_parser.py")

Worked example: an invoice-line parser

The task at the bottom of the file is a small but realistic ETL chore: two vendors send invoice lines in different formats, one with pipes, dollar prices and ISO dates, the other with semicolons, comma decimals, EUR and slashed day-first dates.

INV-0042 | 3 x Widget @ $4.50 | 2026-11-03
inv 43;1x Gadget;12,00 EUR;03/11/2026

Before spending real tokens, I ran the full control flow offline with a fake client that replays canned Interactions responses (the stub is in the companion file stub_test.py). The fake Hydrogen gets the date step wrong twice by reading 03/11/2026 as March 11, which is the classic US/EU ambiguity. The output below is real output from that run, and the token counts in it are canned values, not measured Gemini usage:

PLAN: Parse messy invoice lines into normalized dicts
  1. Normalize money -> parse_money()
  2. Normalize dates -> parse_date()
  3. Parse a line -> parse_line()
[step 1] attempt 1 (medium): PASS
[step 2] attempt 1 (medium): FAIL
[step 2] attempt 2 (high): FAIL
[step 2] handing back to gemini-4-carbon
[step 2] attempt 1 (medium): PASS
[step 3] attempt 1 (medium): PASS
plan       gemini-4-carbon    in=   410 out+think=  2970 $0.0305
build      gemini-4-hydrogen  in=   520 out+think=  1080 $0.0089
build      gemini-4-hydrogen  in=   520 out+think=  1080 $0.0089
build      gemini-4-hydrogen  in=   520 out+think=  1080 $0.0089
replan     gemini-4-carbon    in=   980 out+think=  3340 $0.0354
build      gemini-4-hydrogen  in=   520 out+think=  1080 $0.0089
build      gemini-4-hydrogen  in=   520 out+think=  1080 $0.0089
TOTAL                                                     $0.1103

Carbon's re-plan added one sentence to the instruction: slashed dates are DAY/MONTH/YEAR. That is exactly the kind of fix a planner should own, because the original spec was ambiguous and no amount of retrying at higher thinking would have resolved it. The finished module then parses both vendors' lines:

>>> parse_line("INV-0042 | 3 x Widget @ $4.50 | 2026-11-03")
{'invoice': 'INV-0042', 'qty': 3, 'item': 'Widget', 'unit_price': 4.5, 'currency': 'USD', 'date': '2026-11-03'}
>>> parse_line("inv 43;1x Gadget;12,00 EUR;03/11/2026")
{'invoice': 'INV-0043', 'qty': 1, 'item': 'Gadget', 'unit_price': 12.0, 'currency': 'EUR', 'date': '2026-11-03'}

To run it for real, export your key and run python orchestrator.py. Your plan will differ from mine, since Carbon picks its own step breakdown and asserts, and your token counts will be whatever usage reports.

What the split actually saves

Take the same token counts and price them two ways: the mixed setup above, and the same calls with Carbon doing the builds too. This is a pricing exercise on fixed token counts, not a benchmark. In practice Carbon tends to think more per call, which would widen the gap.

SetupThrough Nov 30From Dec 1
Carbon plans, Hydrogen builds$0.110$0.176
Carbon does everything$0.125$0.250
Saving from the split~12%~30%

The headline is the December column. Once Carbon's introductory pricing ends, every token you move from Carbon to Hydrogen is about 2.7x cheaper on input and output. The other thing the meter makes obvious: the planner and re-planner calls dominate the bill even though there are only two of them. Keeping the planner's job small (plan only, no code) is where most of the saving lives.

A quick helper to reprice any run under a different assignment:

def reprice(meter, as_model):
    p = PRICES[as_model]
    return sum(i / 1e6 * p["in"] + o / 1e6 * p["out"] for _, _, i, o, _ in meter.rows)

Pitfalls and gotchas

  • Hydrogen rejects minimal. If you're migrating from Gemini 3.8 Flash code that set thinking_level: "minimal", Hydrogen returns an error. Use low.
  • Carbon has no xhigh. Carbon's documented levels are low, medium and high. Don't share one config dict between both roles.
  • Hydrogen defaults to high, Carbon to medium. If you omit generation_config, your cheap executor thinks harder by default than your expensive planner. Always set the level explicitly.
  • Settings don't carry across turns. When chaining with previous_interaction_id, tools, system_instruction and generation_config must be re-sent every turn. The loop above avoids the issue by making each step a fresh, self-contained call.
  • Drop temperature, top_p and top_k. Both models ignore in-range values and return 400 for out-of-range ones. Old configs with temperature=2.5 will break.
  • No explicit caching. caches.create and cached_content aren't supported on either model. You get implicit caching only (95% off cached input), so keep stable text such as the plan prompt at the start of the input to help it hit.
  • Old max_output_tokens values truncate thinking. The limit covers thinking plus output. A legacy cap of 8,192 can leave Hydrogen at high with no room to answer and an incomplete status. Google recommends at least 32,768 for Carbon.
  • Long Carbon calls can outlast your HTTP timeout. Google suggests raising client timeouts to around 15 minutes for Carbon or using background=True and polling client.interactions.get(id=...).
  • Don't let the executor write its own tests. If Hydrogen writes both function and asserts, a wrong understanding passes its own wrong tests. The plan owns the asserts for that reason.
  • Bad asserts look like bad code. If Carbon writes an assert that contradicts its own instruction, Hydrogen fails forever. That's why the re-plan prompt explicitly allows fixing asserts, and why there's a hard cap of one re-plan per step.
  • Treat generated code as untrusted. The verifier executes model output. Use a container, a non-privileged user and no network if the task is anything beyond toy parsing.

Quick reference

NeedCode
Pick thinkinggeneration_config={"thinking_level": "medium"}
Typed JSON outresponse_format={"type": "text", "mime_type": "application/json", "schema": Model.model_json_schema()}
Read textinteraction.output_text
Read usageusage.total_input_tokens / total_output_tokens / total_thought_tokens
Chain turnsprevious_interaction_id=prev.id (re-send config)
Long outputbackground=True + max_output_tokens, poll interactions.get(id=...)
Opt out of storagestore=False (no chaining, no background)
Escalate2 failed verifications -> Carbon re-plan at high

Next steps

  • Swap the assert runner for pytest with JSON output so the re-planner gets structured failure data instead of a stack trace.
  • Add a Carbon review pass at the end, as Antigravity does on long tasks, that reads the whole module and flags cross-step issues the per-step tests missed.
  • Try Hydrogen at xhigh as a third retry before escalating. Google reports it scores higher on the Artificial Analysis index (54 vs 51 at high), and it's still cheaper per token than Carbon.
  • Run the build steps that don't depend on each other in parallel threads. The plan already tells you the dependency order.
  • Log every run's meter rows to a CSV and compare against your current single-model setup on a week of real tasks before switching.

Sources

  • Google, Introducing Gemini 4 Hydrogen (blog.google, Nov 12, 2026)
  • Google AI Studio docs: What's new in Gemini 4 Hydrogen; What's new in Gemini 4 Carbon; Interactions overview; Structured output; Thinking
  • Antigravity docs: Models, Orchestrator section; Antigravity blog: Gemini 4 Hydrogen in Google Antigravity
  • Hacker News discussion of the Hydrogen launch (item 50471431)

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,594 builders reading daily.

Also get