Gemini models include a built-in code execution capability that runs Python code in a secure, sandboxed environment. Unlike external code interpreters, this runs directly within the Gemini API call — the model writes code, executes it, and uses the results to formulate its final answer.
Enable it by passing a code_execution tool in your request:
from vertexai.generative_models import GenerativeModel, Tool
model = GenerativeModel(
"gemini-3.5-flash",
tools=[Tool.from_code_execution()]
)
# The model will write and execute Python to solve this
response = model.generate_content(
"Calculate the first 20 Fibonacci numbers and plot them as a line chart."
)
# Response includes the generated chart and computed values
| Task | How Code Execution Helps |
|---|---|
| Math Verification | Model writes Python to verify calculations instead of relying on mental math |
| Data Analysis | Process uploaded CSVs with Pandas, generate statistics |
| Chart Generation | Create matplotlib visualizations inline |
| Algorithm Testing | Write and run code to test algorithmic solutions |