Eksekusi kode

Gemini API menyediakan alat eksekusi kode yang memungkinkan model untuk membuat dan menjalankan kode Python. Model kemudian dapat belajar secara iteratif dari hasil eksekusi kode hingga mencapai output akhir. Anda dapat menggunakan eksekusi kode untuk membuat aplikasi yang mendapatkan manfaat dari penalaran berbasis kode. Misalnya, Anda dapat menggunakan eksekusi kode untuk menyelesaikan persamaan atau memproses teks. Anda juga dapat menggunakan library yang disertakan dalam lingkungan eksekusi kode untuk melakukan tugas yang lebih khusus.

Gemini hanya dapat mengeksekusi kode di Python. Anda masih dapat meminta Gemini untuk membuat kode dalam bahasa lain, tetapi model tidak dapat menggunakan alat eksekusi kode untuk menjalankannya.

Mengaktifkan eksekusi kode

Untuk mengaktifkan eksekusi kode, konfigurasikan alat eksekusi kode pada model. Hal ini memungkinkan model membuat dan menjalankan kode.

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)
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);
  }
});
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())
}
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."
        }
    },
}'

Outputnya mungkin terlihat seperti berikut, yang telah diformat untuk kemudahan membaca:

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.

Output ini menggabungkan beberapa bagian konten yang ditampilkan model saat menggunakan eksekusi kode:

  • text: Teks inline yang dihasilkan oleh model
  • executableCode: Kode yang dihasilkan oleh model yang dimaksudkan untuk dieksekusi
  • codeExecutionResult: Hasil kode yang dapat dieksekusi

Konvensi penamaan untuk bagian ini bervariasi menurut bahasa pemrograman.

Menggunakan eksekusi kode dalam chat

Anda juga dapat menggunakan eksekusi kode sebagai bagian dari chat.

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)
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);
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())
}
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."
            }]
        }
    ]
}'

Input/output (I/O)

Mulai dari Gemini 2.0 Flash, eksekusi kode mendukung input file dan output grafik. Dengan menggunakan kemampuan input dan output ini, Anda dapat mengupload file CSV dan teks, mengajukan pertanyaan tentang file, dan membuat grafik Matplotlib sebagai bagian dari respons. File output ditampilkan sebagai gambar inline dalam respons.

Harga I/O

Saat menggunakan I/O eksekusi kode, Anda akan dikenai biaya untuk token input dan token output:

Token input:

  • Perintah pengguna

Token output:

  • Kode yang dihasilkan oleh model
  • Output eksekusi kode di lingkungan kode
  • Ringkasan yang dibuat oleh model

Detail I/O

Saat Anda menangani I/O eksekusi kode, perhatikan detail teknis berikut:

  • Runtime maksimum lingkungan kode adalah 30 detik.
  • Jika lingkungan kode menghasilkan error, model dapat memutuskan untuk membuat ulang output kode. Hal ini dapat terjadi hingga 5 kali.
  • Ukuran input file maksimum dibatasi oleh periode token model. Di AI Studio, menggunakan Gemini Flash 2.0, ukuran file input maksimum adalah 1 juta token (sekitar 2 MB untuk file teks dari jenis input yang didukung). Jika Anda mengupload file yang terlalu besar, AI Studio tidak akan mengizinkan Anda mengirimkannya.
  • Eksekusi kode berfungsi optimal dengan file teks dan CSV.
  • File input dapat diteruskan dalam part.inlineData atau part.fileData (diupload melalui Files API), dan file output selalu ditampilkan sebagai part.inlineData.
Satu belokan Dua arah (Multimodal Live API)
Model yang didukung Semua model Gemini 2.0 Hanya model eksperimental Flash
Jenis input file yang didukung .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts
Library plot yang didukung Matplotlib Matplotlib
Penggunaan beberapa alat Tidak Ya

Penagihan

Tidak ada biaya tambahan untuk mengaktifkan eksekusi kode dari Gemini API. Anda akan ditagih dengan tarif token input dan output saat ini berdasarkan model Gemini yang Anda gunakan.

Berikut beberapa hal lain yang perlu diketahui tentang penagihan untuk eksekusi kode:

  • Anda hanya ditagih sekali untuk token input yang Anda teruskan ke model, dan Anda ditagih untuk token output akhir yang ditampilkan kepada Anda oleh model.
  • Token yang mewakili kode yang dihasilkan dihitung sebagai token output. Kode yang dihasilkan dapat mencakup teks dan output multimodal seperti gambar.
  • Hasil eksekusi kode juga dihitung sebagai token output.

Model penagihan ditampilkan dalam diagram berikut:

model penagihan eksekusi kode

  • Anda ditagih dengan tarif token input dan output saat ini berdasarkan model Gemini yang Anda gunakan.
  • Jika Gemini menggunakan eksekusi kode saat membuat respons, perintah asli, kode yang dihasilkan, dan hasil kode yang dieksekusi diberi label token perantara dan ditagih sebagai token input.
  • Gemini kemudian membuat ringkasan dan menampilkan kode yang dihasilkan, hasil kode yang dieksekusi, dan ringkasan akhir. Hal ini ditagih sebagai token output.
  • Gemini API menyertakan jumlah token perantara dalam respons API, sehingga Anda tahu mengapa Anda mendapatkan token input tambahan di luar perintah awal.

Batasan

  • Model hanya dapat membuat dan mengeksekusi kode. Metode ini tidak dapat menampilkan artefak lain seperti file media.
  • Dalam beberapa kasus, mengaktifkan eksekusi kode dapat menyebabkan regresi di area lain output model (misalnya, menulis cerita).
  • Ada beberapa variasi dalam kemampuan berbagai model untuk menggunakan eksekusi kode dengan sukses.

Library yang didukung

Lingkungan eksekusi kode mencakup library berikut:

  • attrs
  • catur
  • contourpy
  • fpdf
  • geopandas
  • imageio
  • jinja2
  • joblib
  • jsonschema
  • jsonschema-specifications
  • lxml
  • matplotlib
  • mpmath
  • numpy
  • opencv-python
  • openpyxl
  • paket
  • pandas
  • bantal
  • protobuf
  • pylatex
  • pyparsing
  • PyPDF2
  • python-dateutil
  • python-docx
  • python-pptx
  • reportlab
  • scikit-learn
  • scipy
  • seaborn
  • enam
  • striprtf
  • sympy
  • membuat tabel
  • tensorflow
  • toolz
  • xlrd

Anda tidak dapat menginstal library Anda sendiri.

Langkah berikutnya