GEMINI LABJP
FLASH35 — Gemini 3.5 Flash is now GA and powers gemini-flash-latest, making everyday generation faster and more affordableAGENTS — Managed Agents launch in public preview in the Gemini API, running in secure, isolated Google-hosted Linux sandboxesMEDIA — Nano Banana 2 Lite and Gemini Omni Flash bring faster image and high-quality video generation across AI Studio and the APITTS — Streaming speech generation is now supported for gemini-3.1-flash-tts-preview via streamGenerateContentTRANSLATE — A new audio model detects 70+ languages for live speech-to-speech translation while preserving natural intonationSPENDCAP — Project-level spend caps for billing have been added in Google AI Studio to keep costs under controlFLASH35 — Gemini 3.5 Flash is now GA and powers gemini-flash-latest, making everyday generation faster and more affordableAGENTS — Managed Agents launch in public preview in the Gemini API, running in secure, isolated Google-hosted Linux sandboxesMEDIA — Nano Banana 2 Lite and Gemini Omni Flash bring faster image and high-quality video generation across AI Studio and the APITTS — Streaming speech generation is now supported for gemini-3.1-flash-tts-preview via streamGenerateContentTRANSLATE — A new audio model detects 70+ languages for live speech-to-speech translation while preserving natural intonationSPENDCAP — Project-level spend caps for billing have been added in Google AI Studio to keep costs under control
Articles/API / SDK
API / SDK/2026-07-14Advanced

When Gemini's executed result and its prose disagree on a number — a gate that trusts only code_execution_result

Gemini Code Execution returns the value it actually computed and the sentence describing it as separate parts. Trust the prose and you can inherit a hallucinated number. Here is a verification gate, in working code, that extracts the executed result as the single source of truth and rejects prose that disagrees.

gemini102code-execution4gemini-api274python102verification

Premium Article

Last month I had a quiet scare while letting Gemini aggregate the monthly AdMob report for one of the apps I run as an indie developer. The model wrote, "The weighted-average eCPM is 312.4 yen." I checked it by hand just in case, and the real figure was 287.9. Code Execution was enabled, so the model had actually run Python behind the scenes. Yet the number it computed and the number in the sentence it returned did not match.

Code Execution is usually understood as "the feature that runs code," but that framing misses what matters in production. The real point is this: the value that was actually executed and the natural-language summary of that value come back as separate parts, and they are not guaranteed to agree. If you do not handle them separately, all that accurate sandbox math can still be undone at the last step, where the model transcribes a hallucinated number into its prose.

This article separates those two, extracts the executed result as the single source of truth, and reconciles it against the prose so you can reject answers where they disagree. It is aimed at anyone whose numbers feed real decisions — billing math, report aggregation — while using Code Execution.

Why you cannot trust the model's prose

When Code Execution is enabled, the model goes through a loop: write code, run it, look at the result, then answer in natural language. The API response therefore mixes at least three kinds of parts.

PartContentsTrust level
executable_codePython the model generatedGuaranteed to have run
code_execution_resultThe stdout and outcome the sandbox actually returnedSingle source of truth
textProse summarizing the resultCan hallucinate

The problem is that last one. The model composes its sentence after seeing the result, but during that transcription it can drop a digit or confuse an intermediate value with the final one. The discrepancy I hit was exactly that: the execution result held the correct 287.9, but the prose reported a different intermediate value as if it were the final answer.

In other words, the executed value was right, and it broke on the way into a sentence. To catch this you have to stop reading the prose and mechanically pull out only code_execution_result.

Separating the three response parts

Here is the basic way to receive it. With the google-genai SDK you enable the feature simply by passing the code_execution tool, then sort the returned parts by type.

from google import genai
from google.genai import types
 
client = genai.Client(api_key="YOUR_API_KEY")
 
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents=(
        "Compute the weighted-average eCPM (yen) using impressions as weights. "
        "day1: eCPM=280.0, impressions=12000 / "
        "day2: eCPM=305.0, impressions=8000 / "
        "day3: eCPM=290.0, impressions=15000"
    ),
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution())],
    ),
)
 
executed_code = []      # code the model wrote
execution_outputs = []  # what the sandbox actually printed (truth)
prose = []              # natural-language summary
 
for part in response.candidates[0].content.parts:
    if part.executable_code is not None:
        executed_code.append(part.executable_code.code)
    elif part.code_execution_result is not None:
        execution_outputs.append(part.code_execution_result)
    elif part.text is not None:
        prose.append(part.text)
 
print("executed output:", [r.output for r in execution_outputs])
# executed output: ['288.42105263157896\n']
print("prose:", "".join(prose)[:60])
# prose: The weighted-average eCPM is about 288.4 yen. ...

The key point is that code_execution_result.output is the sandbox's stdout itself, with none of the model's interpretation layered on. That value alone is what you flow downstream.

Also note that the parts do not always arrive as "code, then result, then prose." When the model iterates, executable_code and code_execution_result appear in alternating pairs multiple times. The last execution result is not necessarily the final value, so instead of blindly taking "the last one," design the prompt to make the intended final result explicit, as shown next.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
If you have ever trusted a number in the model's prose and gotten an aggregate wrong, you can now pull out only what the sandbox actually executed and reconcile against it
You get working code that separates the executable_code, code_execution_result, and text parts and rejects hallucinated numbers
You will stop silently swallowing anything other than OUTCOME_OK, and classify failures and timeouts for retry in production
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

API / SDK2026-03-20
Build an AI Data Analysis Agent with Gemini API — Combining Code Execution, Function Calling, and Structured Output
Learn how to build a production-ready AI data analysis agent in Python that combines Gemini API's Code Execution, Function Calling, and Structured Output to automatically analyze CSV/Excel data, generate visualizations, and produce structured reports.
API / SDK2026-07-13
When responseSchema Can't Do $ref: Handling Recursive Schemas in Production with responseJsonSchema
Gemini's responseSchema is an OpenAPI subset with no $ref or $defs, so it can't express shared definitions or recursion. Here's how I moved to responseJsonSchema to reuse localized fields and handle a recursive category tree in production.
API / SDK2026-06-17
Moving My Automation Off the Gemini CLI Before the June 18 Shutdown
On June 18, the Gemini CLI stops responding for hosted plans. Here is how I moved unattended scripts that called gemini from the shell over to the google-genai SDK, with structured output, retries, and cost measurement built in.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →