en un clic
gemini-code-execution
Execute Python code in Gemini's secure sandbox for data analysis, visualization, and file processing
Menu
Execute Python code in Gemini's secure sandbox for data analysis, visualization, and file processing
Production patterns, API key security, cost optimization, performance tuning, and monitoring
Reduce costs and latency with context caching - implicit and explicit cache management with TTL configuration
Generate text embeddings for semantic search, RAG, and vector database integration
Implement robust error handling with retry logic, rate limiting, and circuit breaker patterns
Implement tool use with Gemini - function declarations, tool modes, parallel/compositional calling, and MCP integration
Implement Google Search grounding for real-time information with citation parsing and attribution handling
| name | gemini-code-execution |
| description | Execute Python code in Gemini's secure sandbox for data analysis, visualization, and file processing |
| argument-hint | <computation or analysis task> |
| allowed-tools | Read, Write, Bash(pip install, npm install, go get) |
Execute Python code in a secure sandbox: $ARGUMENTS
You are a Gemini API specialist with expertise in:
from google import genai
from google.genai.types import GenerateContentConfig, Tool, CodeExecution
client = genai.Client()
# Enable code execution tool
code_execution_tool = Tool(code_execution=CodeExecution())
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Calculate the first 20 Fibonacci numbers and find their sum",
config=GenerateContentConfig(tools=[code_execution_tool])
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Calculate the first 20 Fibonacci numbers and find their sum",
tools: [{ codeExecution: {} }]
});
console.log(response.text);
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Generate 100 random numbers and calculate statistics",
config=GenerateContentConfig(tools=[code_execution_tool])
)
# Check response parts for code and output
for part in response.candidates[0].content.parts:
if part.text:
print("Text:", part.text)
elif part.executable_code:
print("Code executed:")
print(part.executable_code.code)
print(f"Language: {part.executable_code.language}")
elif part.code_execution_result:
print("Execution output:")
print(part.code_execution_result.output)
print(f"Outcome: {part.code_execution_result.outcome}") # SUCCESS or FAILED
The sandbox includes 50+ pre-installed libraries:
| Category | Libraries |
|---|---|
| Data Science | numpy, pandas, scipy, sklearn |
| Visualization | matplotlib, seaborn, plotly |
| Math | sympy, statistics, math |
| Text | re, string, textwrap |
| Date/Time | datetime, calendar, time |
| Web | requests, urllib, json |
| Crypto | hashlib, hmac, secrets |
| Collections | collections, itertools, functools |
| I/O | io, csv, pickle |
# Example using multiple libraries
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Using numpy and matplotlib:
1. Generate 1000 samples from a normal distribution
2. Create a histogram
3. Calculate mean and standard deviation
""",
config=GenerateContentConfig(tools=[code_execution_tool])
)
Code execution can read and write files in the sandbox:
from google.genai.types import Part
# Upload a file first
uploaded_file = client.files.upload(file="data.csv")
# Process with code execution
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
Part(file_data={"uri": uploaded_file.uri, "mime_type": "text/csv"}),
Part(text="Read this CSV file and calculate summary statistics for each column")
],
config=GenerateContentConfig(tools=[code_execution_tool])
)
print(response.text)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Generate a CSV file with 100 rows of random user data (name, age, email)",
config=GenerateContentConfig(tools=[code_execution_tool])
)
# Check for generated files
for part in response.candidates[0].content.parts:
if part.code_execution_result:
if part.code_execution_result.files:
for file in part.code_execution_result.files:
print(f"Generated file: {file.name}")
print(f"MIME type: {file.mime_type}")
# File data is base64 encoded
print(f"Data: {file.data[:100]}...")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Create a visualization showing:
1. A sine and cosine wave plot
2. A bar chart of monthly sales data
3. A scatter plot with a trend line
Generate all three as a single figure with subplots.
""",
config=GenerateContentConfig(tools=[code_execution_tool])
)
# Extract generated image
for part in response.candidates[0].content.parts:
if part.inline_data:
# Image is returned as base64
import base64
image_data = base64.b64decode(part.inline_data.data)
with open("chart.png", "wb") as f:
f.write(image_data)
print("Chart saved to chart.png")
from google.genai.types import Part
import base64
# Load image
with open("input_image.jpg", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode()
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents=[
Part(inline_data={"mime_type": "image/jpeg", "data": image_data}),
Part(text="Apply a sepia filter to this image and resize to 800x600")
],
config=GenerateContentConfig(tools=[code_execution_tool])
)
# Extract modified image
for part in response.candidates[0].content.parts:
if part.inline_data:
modified_image = base64.b64decode(part.inline_data.data)
with open("output_image.jpg", "wb") as f:
f.write(modified_image)
# Complex data analysis task
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Create a comprehensive analysis:
1. Generate a dataset of 500 customers with: age, income, spending_score, membership_years
2. Perform K-means clustering (3 clusters)
3. Create visualizations:
- Scatter plot of clusters
- Distribution of each feature
- Correlation heatmap
4. Provide statistical summary
""",
config=GenerateContentConfig(tools=[code_execution_tool])
)
print(response.text)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Solve these mathematical problems with code:
1. Find all prime numbers under 1000
2. Calculate the determinant of a 5x5 random matrix
3. Solve the differential equation dy/dx = x + y with initial condition y(0) = 1
4. Compute the first 50 digits of pi using the Chudnovsky algorithm
""",
config=GenerateContentConfig(tools=[code_execution_tool])
)
from google.genai.types import FunctionDeclaration, Tool
# Custom function for external data
get_stock_data = FunctionDeclaration(
name="get_stock_data",
description="Get historical stock price data",
parameters={
"type": "object",
"properties": {
"symbol": {"type": "string"},
"days": {"type": "integer"}
},
"required": ["symbol"]
}
)
# Combine code execution and functions
combined_tools = Tool(
code_execution=CodeExecution(),
function_declarations=[get_stock_data]
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Get AAPL stock data for the last 30 days and analyze the trend",
config=GenerateContentConfig(tools=[combined_tools])
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Run this intentionally buggy code: print(1/0)",
config=GenerateContentConfig(tools=[code_execution_tool])
)
for part in response.candidates[0].content.parts:
if part.code_execution_result:
if part.code_execution_result.outcome == "FAILED":
print("Execution failed!")
print(f"Error: {part.code_execution_result.output}")
else:
print("Success!")
print(part.code_execution_result.output)
| Limit | Value |
|---|---|
| Execution timeout | 30 seconds |
| Memory | 1 GB |
| File size (input) | 100 MB |
| File size (output) | 25 MB |
| Network access | Disabled |
outcome field for failures| Pattern | Use Case |
|---|---|
| Data analysis | CSV/JSON processing, statistics |
| Visualization | Charts, graphs, plots |
| Math problems | Calculations, equations |
| File transformation | Format conversion, processing |
| Algorithm implementation | Sorting, searching, optimization |
| Model | Code Execution |
|---|---|
| Gemini 3 Pro | Yes |
| Gemini 3 Flash | Yes |
| Gemini 2.5 Pro | Yes |
| Gemini 2.5 Flash | Yes |
| Gemini 2.5 Flash-Lite | No |
For: $ARGUMENTS
Provide: