Code Execution
Gemini Code Execution API - Let Gemini 2.0 write and run Python code. Solve math, data analysis, and complex problems with AI-generated executable code.
Code Execution
Gemini can generate and execute Python code in a sandboxed environment. This is useful for math calculations, data analysis, and tasks that benefit from programmatic solutions.
Supported Models: Code execution is available on Gemini 1.5+ models.
How It Works
- Enable the code execution tool
- Model writes Python code to solve your problem
- Code executes in a secure sandbox
- Results are returned in the response
Enable Code Execution
curl -X POST "https://api.uniterouter.ai/v1beta/models/gemini-2.0-flash:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $UNITEROUTER_API_KEY" \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "Calculate the first 20 Fibonacci numbers"}]
}
],
"tools": [
{
"codeExecution": {}
}
]
}'import google.generativeai as genai
genai.configure(
api_key="your_uniterouter_api_key",
transport="rest",
client_options={"api_endpoint": "api.uniterouter.ai"}
)
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools=["code_execution"]
)
response = model.generate_content(
"Calculate the first 20 Fibonacci numbers"
)
# Print all parts including code and output
for part in response.candidates[0].content.parts:
if hasattr(part, 'executable_code'):
print("Code:")
print(part.executable_code.code)
elif hasattr(part, 'code_execution_result'):
print("Output:")
print(part.code_execution_result.output)
else:
print("Text:", part.text)import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("your_uniterouter_api_key", {
baseUrl: "https://api.uniterouter.ai"
});
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash",
tools: [{ codeExecution: {} }]
});
const result = await model.generateContent(
"Calculate the first 20 Fibonacci numbers"
);
console.log(result.response.text());Response Format
{
"candidates": [{
"content": {
"parts": [
{
"text": "I'll calculate the Fibonacci numbers using Python:"
},
{
"executableCode": {
"language": "PYTHON",
"code": "def fibonacci(n):\n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[-1] + fib[-2])\n return fib[:n]\n\nprint(fibonacci(20))"
}
},
{
"codeExecutionResult": {
"outcome": "OUTCOME_OK",
"output": "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]"
}
},
{
"text": "The first 20 Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181"
}
],
"role": "model"
}
}]
}Available Libraries
The sandbox includes common Python libraries:
| Category | Libraries |
|---|---|
| Math | numpy, scipy, sympy |
| Data | pandas |
| Visualization | matplotlib (saved as images) |
| Standard | math, datetime, collections, itertools |
Use Cases
| Use Case | Example |
|---|---|
| Math | "Solve the equation x^2 - 5x + 6 = 0" |
| Statistics | "Calculate mean and standard deviation of [data]" |
| Data Processing | "Parse this CSV and find the average" |
| Algorithms | "Implement quicksort and sort this list" |
| Conversions | "Convert 100 miles to kilometers" |
Combining with Other Tools
Code execution can be combined with function calling:
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools=[
"code_execution",
{
"function_declarations": [
{
"name": "get_stock_price",
"description": "Get current stock price",
"parameters": {...}
}
]
}
]
)Execution Outcomes
| Outcome | Description |
|---|---|
OUTCOME_OK | Code executed successfully |
OUTCOME_FAILED | Code execution failed |
OUTCOME_DEADLINE_EXCEEDED | Execution timed out |
Limitations
- Timeout: 30 seconds maximum execution time
- Memory: Limited memory allocation
- Network: No network access
- File System: No persistent file system
- Some libraries: Not all Python libraries available
Best Practices
- Clear prompts - Describe what you want calculated
- Provide data - Include data in your prompt for processing
- Iterative - Model can refine code if first attempt fails
- Combine tools - Use with function calling for complex workflows
Related
- Generate Content - Basic generation
- Function Calling - Custom tools
How is this guide?
Function Calling
Gemini Function Calling API - Enable Gemini Pro to call external tools and APIs. Build AI agents with tool use for automated workflows and integrations.
Grounding & Search
Gemini Grounding API - Enhance AI responses with real-time Google Search data. Build fact-checked, up-to-date AI applications with web search integration.