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.
Code execution is available in both AI Studio and the Gemini API. In AI Studio, you can enable code execution in the right panel under Tools. 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:
altair
, chess
, cv2
, matplotlib
, mpmath
, numpy
, pandas
,
pdfminer
, reportlab
, seaborn
, sklearn
, statsmodels
, striprtf
,
sympy
, and tabulate
. You can't install your own libraries.
Before you begin
Before calling the Gemini API, ensure you have your SDK of choice installed, and a Gemini API key configured and ready to use.
Get started with code execution
Enable code execution on the model
You can enable basic code execution as shown here:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d ' {"tools": [{"code_execution": {}}],
"contents": {
"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."
}
},
}'
The output might look something like this:
```python def is_prime(n): """Checks if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(n): """Calculates the sum of the first n prime numbers.""" primes = [] i = 2 while len(primes) < n: if is_prime(i): primes.append(i) i += 1 return sum(primes) # Calculate the sum of the first 50 prime numbers sum_of_first_50_primes = sum_of_primes(50) print(f"The sum of the first 50 prime numbers is: {sum_of_first_50_primes}") ``` **Explanation:** 1. **`is_prime(n)` Function:** - Takes an integer `n` as input. - Returns `False` for numbers less than or equal to 1 (not prime). - Iterates from 2 up to the square root of `n`. If `n` is divisible by any number in this range, it's not prime, and we return `False`. - If the loop completes without finding a divisor, the number is prime, and we return `True`. 2. **`sum_of_primes(n)` Function:** - Takes an integer `n` (number of primes desired) as input. - Initializes an empty list `primes` to store the prime numbers. - Starts a loop, iterating through numbers starting from 2. - For each number `i`, it checks if it's prime using the `is_prime()` function. - If `i` is prime, it's appended to the `primes` list. - The loop continues until the `primes` list has `n` prime numbers. - Finally, it calculates and returns the sum of all the prime numbers in the `primes` list. 3. **Main Part:** - Calls `sum_of_primes(50)` to get the sum of the first 50 prime numbers. - Prints the result. **Output:** ``` The sum of the first 50 prime numbers is: 5117 ```
Use code execution in chat
You can also use code execution as part of a chat.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-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."
}]
}
]
}'
Input/output (I/O)
Starting with Gemini 2.0 Flash, code execution supports file input and graph output. Using these new input and output capabilities, you can upload CSV and text files, ask questions about the files, and have Matplotlib graphs generated as part of the response.
I/O pricing
When using code execution I/O, you're charged for input tokens and output tokens:
Input tokens:
- User prompt
Output tokens:
- Code generated by the model
- Code execution output in the code environment
- Summary generated by the model
I/O details
When you're working with code execution I/O, be aware of the following technical details:
- The maximum runtime of the code environment is 30 seconds.
- If the code environment generates an error, the model may decide to regenerate the code output. This can happen up to 5 times.
- The maximum file input size is limited by the model token window. In AI Studio, using Gemini Flash 2.0, the maximum input file size is 1 million tokens (roughly 2MB for text files of the supported input types). If you upload a file that's too large, AI Studio won't let you send it.
Single turn | Bidirectional (Multimodal Live API) | |
---|---|---|
Models supported | All Gemini 2.0 models | Only Flash experimental models |
File input types supported | .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts | .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts |
Plotting libraries supported | Matplotlib | Matplotlib |
Multi-tool use | No | Yes |
Billing
There'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 the Gemini model you're using.
Here are a few other things to know about billing for code execution:
- You're only billed once for the input tokens you pass to the model, and you're billed for the final output tokens returned to you by the model.
- Tokens representing generated code are counted as output tokens. Generated code can include text and multimodal output like images.
- Code execution results are also counted as output tokens.
The billing model is shown in the following diagram:
- You're billed at the current rate of input and output tokens based on the Gemini model you're using.
- If Gemini uses code execution when generating your response, the original prompt, the generated code, and the result of the executed code are labeled intermediate tokens and are billed as input tokens.
- Gemini then generates a summary and returns the generated code, the result of the executed code, and the final summary. These are billed as output tokens.
- The Gemini API includes an intermediate token count in the API response, so you know why you're getting additional input tokens beyond your initial prompt.
Limitations
- The model can only generate and execute code. It can't return other artifacts like media files.
- In some cases, enabling code execution can lead to regressions in other areas of model output (for example, writing a story).
- There is some variation in the ability of the different models to use code execution successfully.