Kod yürütme

Gemini API, modelin Python kodu oluşturmasını ve çalıştırmasını sağlayan bir kod yürütme aracı sağlar. Ardından model, nihai bir çıkışa ulaşana kadar kod yürütme sonuçlarından iteratif olarak öğrenebilir. Kod tabanlı akıl yürütmeden yararlanan uygulamalar oluşturmak için kod yürütmeyi kullanabilirsiniz. Örneğin, denklemleri çözmek veya metni işlemek için kod yürütmeyi kullanabilirsiniz. Daha özel görevler gerçekleştirmek için kod yürütme ortamına dahil edilen kütüphaneleri de kullanabilirsiniz.

Gemini yalnızca Python'da kod yürütebilir. Gemini'den 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 modeldeki kod yürütme aracını yapılandırın. Bu, modelin kod oluşturmasına ve çalıştırmasına olanak tanır.

Python

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="What is the sum of the first 50 prime numbers? "
    "Generate and run code for the calculation, and make sure you get all 50.",
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution)]
    ),
)

for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    if part.executable_code is not None:
        print(part.executable_code.code)
    if part.code_execution_result is not None:
        print(part.code_execution_result.output)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });

let response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: [
    "What is the sum of the first 50 prime numbers? " +
      "Generate and run code for the calculation, and make sure you get all 50.",
  ],
  config: {
    tools: [{ codeExecution: {} }],
  },
});

const parts = response?.candidates?.[0]?.content?.parts || [];
parts.forEach((part) => {
  if (part.text) {
    console.log(part.text);
  }

  if (part.executableCode && part.executableCode.code) {
    console.log(part.executableCode.code);
  }

  if (part.codeExecutionResult && part.codeExecutionResult.output) {
    console.log(part.codeExecutionResult.output);
  }
});

Go

package main

import (
    "context"
    "fmt"
    "os"
    "google.golang.org/genai"
)

func main() {

    ctx := context.Background()
    client, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    result, _ := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-flash",
        genai.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."),
        config,
    )

    fmt.Println(result.Text())
    fmt.Println(result.ExecutableCode())
    fmt.Println(result.CodeExecutionResult())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_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."
        }
    },
}'

Çıkış, okunabilirlik için biçimlendirilmiş şekilde 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ış, modelin kod yürütme kullanılırken döndürdüğü çeşitli içerik bölümlerini birleştirir:

  • text: Model tarafından oluşturulan satır içi metin
  • executableCode: Model tarafından oluşturulan ve yürütülmesi amaçlanan kod
  • codeExecutionResult: Yürütülebilir kodun sonucu

Bu bölümlerin adlandırma kuralları, programlama diline göre değişir.

Chat'te kod yürütme özelliğini kullanma

Kod yürütme özelliğini sohbet sırasında da kullanabilirsiniz.

Python

from google import genai
from google.genai import types

client = genai.Client()

chat = client.chats.create(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution)]
    ),
)

response = chat.send_message("I have a math question for you.")
print(response.text)

response = chat.send_message(
    "What is the sum of the first 50 prime numbers? "
    "Generate and run code for the calculation, and make sure you get all 50."
)

for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    if part.executable_code is not None:
        print(part.executable_code.code)
    if part.code_execution_result is not None:
        print(part.code_execution_result.output)

JavaScript

import {GoogleGenAI} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });

const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: [
    {
      role: "user",
      parts: [{ text: "I have a math question for you:" }],
    },
    {
      role: "model",
      parts: [{ text: "Great! I'm ready for your math question. Please ask away." }],
    },
  ],
  config: {
    tools: [{codeExecution:{}}],
  }
});

const response = await chat.sendMessage({
  message: "What is the sum of the first 50 prime numbers? " +
            "Generate and run code for the calculation, and make sure you get all 50."
});
console.log("Chat response:", response.text);

Go

package main

import (
    "context"
    "fmt"
    "os"
    "google.golang.org/genai"
)

func main() {

    ctx := context.Background()
    client, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    chat, _ := client.Chats.Create(
        ctx,
        "gemini-2.0-flash",
        config,
        nil,
    )

    result, _ := chat.SendMessage(
                    ctx,
                    genai.Part{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.",
                              },
                )

    fmt.Println(result.Text())
    fmt.Println(result.ExecutableCode())
    fmt.Println(result.CodeExecutionResult())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_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."
            }]
        }
    ]
}'

Giriş/çıkış (G/Ç)

Gemini 2.0 Flash'tan itibaren kod yürütme, dosya girişini 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ıtta satır içi resimler olarak döndürülür.

G/Ç fiyatlandırması

Kod yürütme G/Ç'sini kullandığınızda giriş jetonları ve çıkış jetonları için ücretlendirilirsiniz:

Jeton girme:

  • Kullanıcı istemi

Çıkış jetonları:

  • Model tarafından oluşturulan kod
  • Kod ortamında kod yürütme çıkışı
  • Model tarafından oluşturulan özet

G/Ç ayrıntıları

Kod yürütme G/Ç ile çalışırken aşağıdaki teknik ayrıntılara dikkat edin:

  • Kod ortamının maksimum çalışma süresi 30 saniyedir.
  • Kod ortamı bir hata oluşturursa model, kod çıkışını yeniden oluşturmaya karar verebilir. Bu işlem 5 kez tekrarlanabilir.
  • Maksimum dosya girişi boyutu, model jetonu penceresiyle sınırlıdır. AI Studio'da, Gemini Flash 2.0 kullanılarak oluşturulan maksimum giriş dosyası boyutu 1 milyon parçadır (desteklenen giriş türlerinin metin dosyaları için yaklaşık 2 MB). Çok büyük bir dosya yüklerseniz AI Studio dosyayı göndermenize izin vermez.
  • Kod yürütme işlemi en iyi şekilde metin ve CSV dosyalarında çalışır.
  • Giriş dosyası part.inlineData veya part.fileData olarak iletilebilir (Files API aracılığıyla yüklenir) ve çıkış dosyası her zaman part.inlineData olarak döndürülür.
Tek dönüş İki yönlü (Çok formatlı Live API)
Desteklenen modeller Tüm Gemini 2.0 modelleri Yalnızca Flash deneysel modelleri
Desteklenen dosya giriş türleri .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts
Desteklenen nokta grafik kitaplıkları Matplotlib Matplotlib
Çok amaçlı araç kullanımı Hayır Evet

Faturalandırma

Gemini API'den kod yürütme özelliğinin etkinleştirilmesi için ek ücret alınmaz. Kullandığınız Gemini modeline göre geçerli giriş ve çıkış jetonu ücretiyle faturalandırılırsınız.

Kod yürütmeyle ilgili faturalandırma hakkında bilmeniz gereken diğer noktalar:

  • Modele ilettiğiniz giriş jetonları için yalnızca bir kez faturalandırılırsınız. Model tarafından size döndürülen nihai çıkış jetonları için de faturalandırılırsınız.
  • Oluşturulan kodu temsil eden jetonlar çıkış jetonu olarak sayılır. Oluşturulan kod, metin ve resim gibi çok modlu çı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:

kod yürütme faturalandırma modeli

  • Kullandığınız Gemini modeline göre geçerli giriş ve çıkış jetonu ücretiyle faturalandırılırsınız.
  • Gemini, yanıtınızı oluştururken kod yürütme işlemini kullanıyorsa 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 nihai özeti döndürür. Bunlar çıktı jetonları olarak faturalandırılır.
  • Gemini API, API yanıtında bir ara jeton sayısı içerir. Böylece, ilk isteminizden sonra neden ek giriş jetonları aldığınızı bilirsiniz.

Sınırlamalar

  • Model yalnızca kod oluşturabilir ve çalıştırabilir. Medya dosyaları gibi diğer yapıları döndüremez.
  • Bazı durumlarda kod yürütmeyi etkinleştirmek, model çıktısının diğer alanlarında (ör. hikaye yazma) gerilemelere neden olabilir.
  • Farklı modellerin kod yürütmeyi başarılı bir şekilde kullanma becerisinde bazı farklılıklar vardır.

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
  • tablo oluşturma
  • tensorflow
  • toolz
  • xlrd

Kendi kitaplıklarınızı yükleyemezsiniz.

Sırada ne var?