Stay organized with collections Save and categorize content based on your preferences.
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.
The code execution environment includes the following libraries. You can't install your own libraries.
The following models provide support for code execution:
This section assumes that you've completed the setup and configuration steps shown in the Gemini API quickstart.
Enable code execution on the modelYou can enable basic code execution as shown here:
Python Installpip install --upgrade google-genai
To learn more, see the SDK reference documentation.
Set environment variables to use the Gen AI SDK with Vertex AI:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=TrueGo
Learn how to install or update the Go.
To learn more, see the SDK reference documentation.
Set environment variables to use the Gen AI SDK with Vertex AI:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=TrueNode.js Install
npm install @google/genai
To learn more, see the SDK reference documentation.
Set environment variables to use the Gen AI SDK with Vertex AI:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=TrueREST
Before using any of the request data, make the following replacements:
GENERATE_RESPONSE_METHOD
: The type of response that you want the model to generate. Choose a method that generates how you want the model's response to be returned:
streamGenerateContent
: The response is streamed as it's being generated to reduce the perception of latency to a human audience.generateContent
: The response is returned after it's fully generated.LOCATION
: The region to process the request. Available options include the following:
Click to expand a partial list of available regions
us-central1
us-west4
northamerica-northeast1
us-east4
us-west1
asia-northeast3
asia-southeast1
asia-northeast1
PROJECT_ID
: Your project ID.MODEL_ID
: The model ID of the model that you want to use.ROLE
: The role in a conversation associated with the content. Specifying a role is required even in singleturn use cases. Acceptable values include the following:
USER
: Specifies content that's sent by you.MODEL
: Specifies the model's response.TEXTThe text instructions to include in the prompt.
To send your request, choose one of these options:
curl Note: The following command assumes that you have logged in to thegcloud
CLI with your user account by running gcloud init
or gcloud auth login
, or by using Cloud Shell, which automatically logs you into the gcloud
CLI . You can check the currently active account by running gcloud auth list
.
Save the request body in a file named request.json
. Run the following command in the terminal to create or overwrite this file in the current directory:
cat > request.json << 'EOF' { "tools": [{'codeExecution': {}}], "contents": { "role": "ROLE", "parts": { "text": "TEXT" } }, } EOF
Then execute the following command to send your REST request:
curl -X POST \PowerShell Note: The following command assumes that you have logged in to the
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"
gcloud
CLI with your user account by running gcloud init
or gcloud auth login
. You can check the currently active account by running gcloud auth list
.
Save the request body in a file named request.json
. Run the following command in the terminal to create or overwrite this file in the current directory:
@' { "tools": [{'codeExecution': {}}], "contents": { "role": "ROLE", "parts": { "text": "TEXT" } }, } '@ | Out-File -FilePath request.json -Encoding utf8
Then execute the following command to send your REST request:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content
You should receive a JSON response similar to the following.
Response{ "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Okay, I understand. You want me to calculate the sum of the first 10 positive integers and to use code to do so. Here's my plan: I will use a loop to add the numbers from 1 to 10 and then return the final sum.\n\n" }, { "executableCode": { "language": "PYTHON", "code": "\ntotal = 0\nfor i in range(1, 11):\n total += i\nprint(f'{total=}')\n" } }, { "codeExecutionResult": { "outcome": "OUTCOME_OK", "output": "total=55\n" } }, { "text": "The sum of the first 10 positive numbers is 55.\n" } ] }, "finishReason": "STOP", "safetyRatings": [ { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE", "probabilityScore": 0.19436789, "severity": "HARM_SEVERITY_NEGLIGIBLE", "severityScore": 0.17441037 }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE", "probabilityScore": 0.0685376, "severity": "HARM_SEVERITY_NEGLIGIBLE", "severityScore": 0.14903527 }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE", "probabilityScore": 0.23231025, "severity": "HARM_SEVERITY_LOW", "severityScore": 0.2436427 }, { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE", "probabilityScore": 0.08269742, "severity": "HARM_SEVERITY_NEGLIGIBLE", "severityScore": 0.10818888 } ], "score": -0.50845032930374146, "avgLogprobs": -0.0046222757209431042 } ], "usageMetadata": { "promptTokenCount": 34, "candidatesTokenCount": 110, "totalTokenCount": 144, "billablePromptUsage": { "textCount": 119 }, "trafficType": "ON_DEMAND" }, "modelVersion": "gemini-2.0-flash-001", "createTime": "2024-12-09T23:33:47.842964Z", "responseId": "W35XZ9S5M6acmecP3vDFkQU" }Use code execution in chat
You can also use code execution as part of a chat.
RESTcurl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/test-project/locations/global/publishers/google/models/gemini-2.0-flash-001:generateContent -d \
$'{
"tools": [{'code_execution': {}}],
"contents": [
{
"role": "user",
"parts": {
"text": "Can you print \"Hello world!\"?"
}
},
{
"role": "model",
"parts": [
{
"text": ""
},
{
"executable_code": {
"language": "PYTHON",
"code": "\nprint(\"hello world!\")\n"
}
},
{
"code_execution_result": {
"outcome": "OUTCOME_OK",
"output": "hello world!\n"
}
},
{
"text": "I have printed \"hello world!\" using the provided python code block. \n"
}
],
},
{
"role": "user",
"parts": {
"text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50."
}
}
]
}'
Code execution versus function calling
Code execution and function calling are similar features:
In general, you should prefer to use code execution if it can handle your use case. Code execution is simpler to use (you just enable it) and resolves in a single GenerateContent
request. Function calling takes an additional GenerateContent
request to send back the output from each function call.
For most cases, you should use function calling if you have your own functions that you want to run locally, and you should use code execution if you'd like the API to write and run Python code for you and return the result.
BillingThere's no additional charge for enabling code execution from the Gemini API. You'll be billed at the current rate of input and output tokens based on what Gemini model you're using.
Here are a few other things to know about billing for code execution:
Generated code can include both text and multimodal outputs, such as images.
Limitations.cpp
, .csv
, .java
, .jpeg
, .js
, .png
, .py
, .ts
, and .xml
.Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-14 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-14 UTC."],[],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4