Kod yürütme
Gemini API, modelin Python kodu oluşturup çalıştırmasını sağlayan bir kod yürütme aracı sunar. Model daha sonra nihai bir çıkışa ulaşana kadar kod yürütme sonuçlarından yinelemeli olarak öğrenebilir. Kod yürütme özelliğini kullanarak kod tabanlı akıl yürütmeden yararlanan uygulamalar oluşturabilirsiniz. Örneğin, denklem çözmek veya metin işlemek için kod yürütmeyi kullanabilirsiniz. Daha özel görevleri gerçekleştirmek için kod yürütme ortamında yer alan kütüphaneleri de kullanabilirsiniz.
Gemini yalnızca Python'daki kodları çalıştırabilir. Gemini'dan başka bir dilde kod oluşturmasını isteyebilirsiniz ancak model, kodu çalıştırmak için kod yürütme aracını kullanamaz.
Kod yürütmeyi etkinleştirme
Kod yürütmeyi etkinleştirmek için modelde kod yürütme aracını yapılandırın. Bu, modelin kod oluşturup çalıştırmasına olanak tanır.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What is the sum of the first 50 prime numbers? "
"Generate and run code for the calculation, and make sure you get all 50.",
tools=[{"type": "code_execution"}]
)
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
elif step.type == "code_execution_call":
print(step.arguments.code)
elif step.type == "code_execution_result":
print(step.result)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.",
tools: [{ type: "code_execution" }]
});
for (const step of interaction.steps) {
if (step.type === "model_output") {
for (const contentBlock of step.content) {
if (contentBlock.type === "text") {
console.log(contentBlock.text);
}
}
} else if (step.type === "code_execution_call") {
console.log(step.arguments.code);
} else if (step.type === "code_execution_result") {
console.log(step.result);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.",
"tools": [{"type": "code_execution"}]
}'
Çıkış, okunabilirlik için biçimlendirilmiş aşağıdaki gibi görünebilir:
Okay, I need to calculate the sum of the first 50 prime numbers. Here's how I'll
approach this:
1. **Generate Prime Numbers:** I'll use an iterative method to find prime
numbers. I'll start with 2 and check if each subsequent number is divisible
by any number between 2 and its square root. If not, it's a prime.
2. **Store Primes:** I'll store the prime numbers in a list until I have 50 of
them.
3. **Calculate the Sum:** Finally, I'll sum the prime numbers in the list.
Here's the Python code to do this:
def is_prime(n):
"""Efficiently checks if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
primes = []
num = 2
while len(primes) < 50:
if is_prime(num):
primes.append(num)
num += 1
sum_of_primes = sum(primes)
print(f'{primes=}')
print(f'{sum_of_primes=}')
primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]
sum_of_primes=5117
The sum of the first 50 prime numbers is 5117.
Bu çıkış, kod yürütme kullanılırken modelin döndürdüğü çeşitli içerik bölümlerini birleştirir:
text: Model tarafından oluşturulan satır içi metincode_execution_call: Model tarafından oluşturulan ve yürütülmesi amaçlanan kodcode_execution_result: Yürütülebilir kodun sonucu
Görüntülerle kod yürütme (Gemini 3)
Gemini 3 Flash modeli artık görüntüleri etkin bir şekilde işlemek ve incelemek için Python kodu yazıp çalıştırabilir.
Kullanım alanları
- Yakınlaştırma ve inceleme: Model, ayrıntıların çok küçük olduğunu (ör. uzaktaki bir göstergeyi okuma) örtülü olarak algılar ve alanı kırpıp daha yüksek çözünürlükte yeniden incelemek için kod yazar.
- Görsel matematik: Model, kod kullanarak çok adımlı hesaplamalar yapabilir (ör. bir makbuzdaki satır öğelerini toplama).
- Görüntü notlandırma: Model, soruları yanıtlamak için görüntüleri notlandırabilir (ör. ilişkileri göstermek için ok çizme).
Görüntülerle kod yürütmeyi etkinleştirme
Görüntülerle kod yürütme, Gemini 3 Flash'te resmi olarak desteklenir. Hem "Araç olarak kod yürütme" hem de "Düşünme"yi etkinleştirerek bu davranışı etkinleştirebilirsiniz.
Python
from google import genai
import requests
import base64
from PIL import Image
import io
image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "image", "data": base64.b64encode(image_bytes).decode('utf-8'), "mime_type": "image/jpeg"},
{"type": "text", "text": "Zoom into the expression pedals and tell me how many pedals are there?"}
],
tools=[{"type": "code_execution"}]
)
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
elif content_block.type == "image":
# Display generated image
display(Image.open(io.BytesIO(base64.b64decode(content_block.data))))
elif step.type == "code_execution_call":
print(step.arguments.code)
elif step.type == "code_execution_result":
print(step.result)
JavaScript
async function main() {
const client = new GoogleGenAI({});
// 1. Prepare Image Data
const imageUrl = "https://goo.gle/instrument-img";
const response = await fetch(imageUrl);
const imageArrayBuffer = await response.arrayBuffer();
const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64');
// 2. Call the API with Code Execution enabled
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{
type: "image",
data: base64ImageData,
mimeType: "image/jpeg"
},
{ type: "text", text: "Zoom into the expression pedals and tell me how many pedals are there?" }
],
tools: [{ type: "code_execution" }]
});
// 3. Process the response (Text, Code, and Execution Results)
for (const step of interaction.steps) {
if (step.type === "model_output") {
for (const contentBlock of step.content) {
if (contentBlock.type === "text") {
console.log("Text:", contentBlock.text);
}
}
} else if (step.type === "code_execution_call") {
console.log(`\nGenerated Code:\n`, step.arguments.code);
} else if (step.type === "code_execution_result") {
console.log(`\nExecution Output:\n`, step.result);
}
}
}
main();
REST
IMG_URL="https://goo.gle/instrument-img"
MODEL="gemini-3-flash-preview"
MIME_TYPE=$(curl -sIL "$IMG_URL" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\r$//' | head -n 1)
if [[ -z "$MIME_TYPE" || ! "$MIME_TYPE" == image/* ]]; then
MIME_TYPE="image/jpeg"
fi
if [[ "$(uname)" == "Darwin" ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -b 0)
elif [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64)
else
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -w0)
fi
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"type": "image",
"data": "'"$IMAGE_B64"'",
"mime_type": "'"$MIME_TYPE"'"
},
{"type": "text", "text": "Zoom into the expression pedals and tell me how many pedals are there?"}
],
"tools": [{"type": "code_execution"}]
}'
Çok turlu etkileşimlerde kod yürütme özelliğini kullanma
Ayrıca, previous_interaction_id kullanarak çok turlu bir görüşmenin parçası olarak kod yürütme özelliğini de kullanabilirsiniz.
Python
from google import genai
client = genai.Client()
# First turn
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input="I have a math question for you.",
tools=[{"type": "code_execution"}]
)
print(interaction1.steps[-1].content[0].text)
# Second turn - follow-up with code execution
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
previous_interaction_id=interaction1.id,
input="What is the sum of the first 50 prime numbers? "
"Generate and run code for the calculation, and make sure you get all 50.",
tools=[{"type": "code_execution"}]
)
for step in interaction2.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
elif step.type == "code_execution_call":
print(step.arguments.code)
elif step.type == "code_execution_result":
print(step.result)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// First turn
const interaction1 = await client.interactions.create({
model: "gemini-3-flash-preview",
input: "I have a math question for you.",
tools: [{ type: "code_execution" }]
});
console.log(interaction1.steps.at(-1).content[0].text);
// Second turn - follow-up with code execution
const interaction2 = await client.interactions.create({
model: "gemini-3-flash-preview",
previousInteractionId: interaction1.id,
input: "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.",
tools: [{ type: "code_execution" }]
});
for (const step of interaction2.steps) {
if (step.type === "model_output") {
for (const contentBlock of step.content) {
if (contentBlock.type === "text") {
console.log(contentBlock.text);
}
}
} else if (step.type === "code_execution_call") {
console.log(step.arguments.code);
} else if (step.type === "code_execution_result") {
console.log(step.result);
}
}
REST
# First turn
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": "I have a math question for you.",
"tools": [{"type": "code_execution"}]
}')
INTERACTION_ID=$(echo $RESPONSE1 | jq -r '.id')
# Second turn with previous_interaction_id
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"previous_interaction_id": "'"$INTERACTION_ID"'",
"input": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.",
"tools": [{"type": "code_execution"}]
}'
Giriş/çıkış (G/Ç)
Gemini 2.0 Flash'tan itibaren kod yürütme, dosya girişi ve grafik çıkışını destekler. Bu giriş ve çıkış özelliklerini kullanarak CSV ve metin dosyaları yükleyebilir, dosyalarla ilgili sorular sorabilir ve yanıtın bir parçası olarak Matplotlib grafikleri oluşturabilirsiniz. Çıkış dosyaları, yanıttaki satır içi resimler olarak döndürülür.
G/Ç fiyatlandırması
Kod yürütme G/Ç'sini kullanırken giriş jetonları ve çıkış jetonları için ücretlendirilirsiniz:
Giriş jetonları:
- Kullanıcı istemi
Çıkış jetonları:
- Model tarafından oluşturulan kod
- Kod ortamında kod yürütme çıkışı
- Düşünme jetonları
- Model tarafından oluşturulan özet
G/Ç ayrıntıları
Kod yürütme G/Ç'siyle çalışırken aşağıdaki teknik ayrıntılara dikkat edin:
- Kod ortamının maksimum çalışma süresi 30 saniyedir.
- Kod ortamı hata oluşturursa model, kod çıkışını yeniden oluşturmaya karar verebilir. Bu durum en fazla 5 kez yaşanabilir.
- Maksimum dosya giriş boyutu, model jetonu penceresiyle sınırlıdır. AI Studio'da Gemini Flash 2.0 kullanılırken maksimum giriş dosyası boyutu 1 milyon jetondur (desteklenen giriş türlerindeki metin dosyaları için yaklaşık 2 MB). Çok büyük bir dosya yüklerseniz AI Studio bu dosyayı göndermenize izin vermez.
- Kod yürütme, metin ve CSV dosyalarıyla en iyi şekilde çalışır.
- Giriş dosyası satır içi veri olarak iletilebilir veya Files API kullanılarak yüklenebilir. Çıkış dosyası ise her zaman satır içi veri olarak döndürülür.
Faturalandırma
Gemini API'den kod yürütmeyi etkinleştirmek için ek ücret alınmaz. Kullandığınız Gemini modeline göre giriş ve çıkış jetonlarının mevcut oranı üzerinden faturalandırılırsınız.
Kod yürütme faturalandırması hakkında bilmeniz gereken diğer noktalar:
- Modele ilettiğiniz giriş jetonları için yalnızca bir kez faturalandırılırsınız ve model tarafından size döndürülen nihai çıkış jetonları için faturalandırılırsınız.
- Oluşturulan kodu temsil eden jetonlar, çıkış jetonları olarak sayılır. Oluşturulan kod, metin ve resim gibi çok formatlı çıkışlar içerebilir.
- Kod yürütme sonuçları da çıkış jetonu olarak sayılır.
Faturalandırma modeli aşağıdaki şemada gösterilmektedir:

- Kullandığınız Gemini modeline göre giriş ve çıkış jetonlarının mevcut oranı üzerinden faturalandırılırsınız.
- Gemini, yanıtınızı oluştururken kod yürütme özelliğini kullanırsa orijinal istem, oluşturulan kod ve yürütülen kodun sonucu ara jetonları olarak etiketlenir ve giriş jetonları olarak faturalandırılır.
- Ardından Gemini, bir özet oluşturur ve oluşturulan kodu, çalıştırılan kodun sonucunu ve son özeti döndürür. Bunlar çıkış jetonları olarak faturalandırılır.
- Gemini API, API yanıtında ara jeton sayısını içerir. Böylece, ilk isteminizin ötesinde neden ek giriş jetonları aldığınızı bilirsiniz.
Sınırlamalar
- Model yalnızca kod oluşturabilir ve yürütebilir. Medya dosyaları gibi diğer öğeler döndürülemez.
- Bazı durumlarda, kod yürütmenin etkinleştirilmesi model çıktısının diğer alanlarında (ör. hikaye yazma) gerilemelere yol açabilir.
- Farklı modellerin kod yürütmeyi başarılı bir şekilde kullanma becerisinde bazı farklılıklar vardır.
Desteklenen araç kombinasyonları
Kod yürütme aracı, daha karmaşık kullanım alanlarını desteklemek için Google Arama ile Temellendirme ile birleştirilebilir.
Gemini 3 modelleri, yerleşik araçların (ör. Kod Yürütme) özel araçlarla (işlev çağrısı) birleştirilmesini destekler.
Desteklenen kitaplıklar
Kod yürütme ortamı aşağıdaki kitaplıkları içerir:
- attrs
- satranç
- contourpy
- fpdf
- geopandas
- imageio
- jinja2
- joblib
- jsonschema
- jsonschema-specifications
- lxml
- matplotlib
- mpmath
- numpy
- opencv-python
- openpyxl
- paketleme
- pandalar
- yastık
- protobuf
- pylatex
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- reportlab
- scikit-learn
- scipy
- seaborn
- altı
- striprtf
- sympy
- tablolaştırmak
- tensorflow
- toolz
- xlrd
Kendi kitaplıklarınızı yükleyemezsiniz.
Sırada ne var?
- Şunu deneyin:
- Diğer Gemini API araçları hakkında bilgi edinin: