Built-in Code Execution: Sandboxing Model-Written Python in ADK
Letting Gemini write and run Python inside an ADK agent: how the code_executor pipeline works, choosing between BuiltInCodeExecutor, Container, GKE, Vertex AI, and Cloud Run sandboxes, configuration options, and the limitations that bite.
Published on • November 27, 2026
AI Assistant

Ask a model for an exact calculation, a chart, or a transformation over a 200-row CSV and the honest answer is: it should write code and run it rather than guess. Code execution turns that into an agent capability — but the moment a model can run code on your infrastructure, “where does it run” becomes a security question, not a plumbing one.
This tutorial covers the two ways to get code execution in this stack — the Gen AI SDK’s built-in tool and ADK’s code_executor pipeline — and spends most of its length on the part that matters: choosing an executor and configuring its limits.
Option A: the built-in tool in the Gen AI SDK
At the SDK level, code execution is a managed tool on the request:
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Plot the monthly revenue trend from these numbers: ...',
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution())],
),
)
for part in response.parts:
if part.executable_code: # the code the model wrote
print(part.executable_code.code)
if part.code_execution_result: # stdout / outcome
print(part.code_execution_result.output, part.code_execution_result.outcome)
Execution happens provider-side: the model proposes code, the API runs it in a sandbox, and both the code and its result come back as parts. There is no infrastructure for you to operate — and no control over the environment either.
Option B: ADK’s code_executor
ADK turns the same capability into an agent-level decision. You attach an executor, and the rest happens during the agent’s own turn:
from google.adk.agents import LlmAgent
from google.adk.code_executors import UnsafeLocalCodeExecutor
agent = LlmAgent(
name='calculator_agent',
instruction='When asked a math problem, write Python code to compute the exact result.',
code_executor=UnsafeLocalCodeExecutor(timeout_seconds=30),
)
Ask it “what is 6 times 7?” and it writes print(6 * 7) in a Python block. The user never sees the block — ADK pulls it out, runs it, and feeds the result back to the model, which then answers in words.
The pipeline
- Extraction. The model’s text is scanned for delimiters (
```pythonor```tool_code). The first block becomes executable code; everything after it in that response is discarded. - Execution. Code plus session-attached files go to
code_executor.execute_code(...). - Result formatting.
stdout,stderr, and output files come back as a code-execution result part withOUTCOME_OKorOUTCOME_FAILED. - Retry on error. Non-empty
stderrcounts as a failed run; up toerror_retry_attempts(default 2) consecutive failures feed the error back for the model to fix. - Replay as text. On later model calls, earlier code/result parts are rewritten as plain text so models without native code-execution parts can still read the history.
Configuration
| Option | Default | Notes |
|---|---|---|
error_retry_attempts | 2 | Bounds the self-correction loop |
code_block_delimiters | ```tool_code / ```python | What counts as executable |
execution_result_delimiters | ```tool_output | How results replay as text |
timeout_seconds | None | Set this. The default waits forever |
stateful | False | Variables persist across executions (backend must support it) |
optimize_data_file | False | Pull text/csv parts from the message into the execution input |
Choosing an implementation
Seven executors ship in the box; they differ almost entirely in who runs the code and how much they isolate it:
| Executor | Where it runs | Isolation | Choose when |
|---|---|---|---|
UnsafeLocalCodeExecutor | Your host, child interpreter | None | Local development, only you shape the prompt |
ContainerCodeExecutor | Docker container (network off, caps dropped) | Container | You want a boundary and run Docker |
GkeCodeExecutor | gVisor-sandboxed K8s pods | Kernel sandbox | You operate Kubernetes |
BuiltInCodeExecutor | Gemini’s server-side execution | Provider-run | No infra to operate; model must support it |
VertexAiCodeExecutor | Vertex AI Code Interpreter extension | Provider-run | Managed Vertex workloads |
AgentEngineSandboxCodeExecutor | Agent Engine sandbox env | Provider-run | Already on Agent Engine |
CloudRunSandboxCodeExecutor | sandbox binary in your Cloud Run container | Guest sandbox | Agent runs in Cloud Run with sandboxes enabled |
The decision order from the docs is the right one: ask who can influence the prompt. If only your team writes to the agent, local execution is a fair trade while you develop. If anyone else can reach it — other users, tool output containing third-party text, a web form — you need a boundary, and then the question is whether you operate that boundary or a provider does.
Note pip install "google-adk[extensions]" for VertexAiCodeExecutor, ContainerCodeExecutor, GkeCodeExecutor, and AgentEngineSandboxCodeExecutor; imports succeed without it, but construction is where it fails.
Security realities
UnsafeLocalCodeExecutorinherits your process’s identity: environment variables, credentials, network, filesystem. Never expose it to untrusted input — an injected instruction becomes arbitrary code execution with your privileges.- Model-written code is unreviewed by definition. Prompt influence (user text, retrieved documents, tool output) flows into the code. Sandboxing is the control; treating prompts as trusted input is not.
- Set
timeout_secondseverywhere. Awhile True:in model output should not hang an agent; implementations enforce this differently (process sessions locally, alarms in containers, watches in Kubernetes), but the base default isNone. - Disable egress by default where the executor supports it — sandboxed code with network access is still an exfiltration channel.
Practical guidance
- Instruct for a single block per turn. Only the first block runs; tell the model to write one snippet and iterate on the result, or its second thought is silently dropped.
- Turn on
error_retry_attemptsdeliberately. Two retries catch most off-by-one bugs; ten burns tokens re-running the same broken code. - Decide about
stateful. Stateless means re-importing and re-loading each snippet (slow, but hermetic); stateful is faster for exploratory analysis and harder to reason about. Note three implementations rejectstatefulandoptimize_data_fileoutright with aValueErrorat construction. - Budget the tokens. Code, outputs, and retries all land in the conversation — code execution inflates context fast; cap it like any other tool (token budgeting).
- Measure latency. A container cold-start per snippet can dominate turn time; provision or choose a warm executor if the path is interactive.
Takeaways
- Two entry points: the Gen AI SDK’s built-in
code_executiontool for direct calls, and ADK’scode_executorfor agents — the latter gives you control over where code runs. - The pipeline is extract → execute → format → bounded retry → replay as text; only the first code block runs.
- Choose the executor from the trust question: local (dev), your own containers/gVisor, or provider-run sandboxes (BuiltIn/Vertex/Agent Engine/Cloud Run).
- Always set a timeout, prefer non-privileged and no-egress defaults, and never point local execution at untrusted input.
- Instruct the model to write one block per turn, and budget the context cost of code + results.