UniterRouter
API ReferenceGoogle Compatible

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

  1. Enable the code execution tool
  2. Model writes Python code to solve your problem
  3. Code executes in a secure sandbox
  4. 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:

CategoryLibraries
Mathnumpy, scipy, sympy
Datapandas
Visualizationmatplotlib (saved as images)
Standardmath, datetime, collections, itertools

Use Cases

Use CaseExample
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

OutcomeDescription
OUTCOME_OKCode executed successfully
OUTCOME_FAILEDCode execution failed
OUTCOME_DEADLINE_EXCEEDEDExecution 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

  1. Clear prompts - Describe what you want calculated
  2. Provide data - Include data in your prompt for processing
  3. Iterative - Model can refine code if first attempt fails
  4. Combine tools - Use with function calling for complex workflows

How is this guide?