Execute code with the Gemini Enterprise API

The Gemini API code execution feature enables the model to generate and run Python code and learn iteratively from the results until it arrives at a final output. You can use this code execution capability to build applications that benefit from code-based reasoning and that produce text output. For example, you could use code execution in an application that solves equations or processes text.

The Gemini API provides code execution as a tool, similar to function calling. After you add code execution as a tool, the model decides when to use it.

Supported models

Model Version
Gemini 2.0 Flash gemini-2.0-flash-001

Limitations

  • The feature doesn't support file I/O.
  • Code execution can run for a maximum of 30 seconds before timing out.

Example syntax

curl

PROJECT_ID = myproject
REGION = us-central1
MODEL_ID = gemini-2.0-flash-001

https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      ...
    }],
    "tools": [{
      "code_execution":  {}
    }]
  }'

Python

from google import genai
from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig

client = genai.Client()
model_id = "gemini-2.0-flash-001"

code_execution_tool = Tool(
    code_execution=ToolCodeExecution()
)
response = client.models.generate_content(
    model=model_id,
    contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
    config=GenerateContentConfig(
        tools=[code_execution_tool],
        temperature=0,
    ),
)

Parameter list

See examples for implementation details.

Python

To enable code execution, specify a code execution tool in your request.

CodeExecution

Tool that executes code generated by the model, and automatically returns the result to the model. See also ExecutableCode and CodeExecutionResult which are input and output to this tool.

Part

executable_code

Optional: ExecutableCode

Code generated by the model that is meant to be executed.
See Code Execution [API].

code_execution_result

Optional: CodeExecutionResult

Result of executing the [ExecutableCode].
See Code Execution [API].

ExecutableCode

language

Required: string (enum)

Supported programming languages for the generated code.


Supported:
  • PYTHON

code

Required: string

The code to be executed.
See Code Execution [API].

CodeExecutionResult

outcome

Required: string (enum)

Outcome of the code execution.


Possible outcomes:
  • Code execution completed successfully. (OUTCOME_OK)
  • Code execution finished but with a failure. stderr should contain the reason. (OUTCOME_FAILED)
  • Code execution ran for too long, and was cancelled. There may or may not be a partial output present. (OUTCOME_DEADLINE_EXCEEDED)

output

Required: string

Contains stdout when code execution is successful, stderr or other description otherwise.
See Code Execution [API].

Examples

Here are illustrations of how you can submit a query and function declarations to the model.

Basic use case

curl

PROJECT_ID = myproject
REGION = us-central1
MODEL_ID = gemini-2.0-flash-001

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "Calculate 20th fibonacci number. Then find the nearest palindrome to it." 
      }]
    }],
    "tools": [{'codeExecution': {}}],
  }'

Python

from google import genai
from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig

client = genai.Client()
model_id = "gemini-2.0-flash-001"

code_execution_tool = Tool(
    code_execution=ToolCodeExecution()
)
response = client.models.generate_content(
    model=model_id,
    contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
    config=GenerateContentConfig(
        tools=[code_execution_tool],
        temperature=0,
    ),
)
for part in response.candidates[0].content.parts:
    if part.executable_code:
        print(part.executable_code)
    if part.code_execution_result:
        print(part.code_execution_result)
# Example response:
# code='...' language='PYTHON'
# outcome='OUTCOME_OK' output='The 20th Fibonacci number is: 6765\n'
# code='...' language='PYTHON'
# outcome='OUTCOME_OK' output='Lower Palindrome: 6666\nHigher Palindrome: 6776\nNearest Palindrome to 6765: 6776\n'

Enable code execution on the model

To enable basic code execution, see Code execution.

What's next