Eksekusi kode


Eksekusi kode adalah alat yang memungkinkan model membuat dan menjalankan kode Python. Model dapat belajar secara iteratif dari hasil eksekusi kode hingga mencapai output akhir.

Anda dapat menggunakan eksekusi kode untuk membuat fitur yang memanfaatkan penalaran berbasis kode dan yang menghasilkan output teks. 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.

Sama seperti semua alat yang Anda berikan ke model, model akan memutuskan kapan harus menggunakan eksekusi kode.

Langsung ke penerapan kode

Perbandingan eksekusi kode versus panggilan fungsi

Eksekusi kode dan panggilan fungsi adalah fitur yang serupa. Secara umum, sebaiknya gunakan eksekusi kode jika model dapat menangani kasus penggunaan Anda. Eksekusi kode juga lebih mudah digunakan karena Anda hanya perlu mengaktifkannya.

Berikut beberapa perbedaan tambahan antara eksekusi kode dan pemanggilan fungsi:

Eksekusi kode Panggilan fungsi
Gunakan eksekusi kode jika Anda ingin model menulis dan menjalankan kode Python untuk Anda serta menampilkan hasilnya. Gunakan panggilan fungsi jika Anda sudah memiliki fungsi sendiri yang ingin dijalankan secara lokal.
Eksekusi kode memungkinkan model menjalankan kode di backend API dalam lingkungan tetap dan terisolasi. Dengan panggilan fungsi, Anda dapat menjalankan fungsi yang diminta model, di lingkungan apa pun yang Anda inginkan.
Eksekusi kode diselesaikan dalam satu permintaan. Meskipun Anda dapat secara opsional menggunakan eksekusi kode dengan kemampuan chat, tidak ada persyaratan untuk melakukannya. Panggilan fungsi memerlukan permintaan tambahan untuk mengirim kembali output dari setiap panggilan fungsi. Oleh karena itu, Anda harus menggunakan kemampuan chat.

Model yang didukung

  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite
  • gemini-2.0-flash-001 (dan aliasnya yang diupdate otomatis gemini-2.0-flash)
  • gemini-2.0-flash-live-preview-04-09

Menggunakan eksekusi kode

Anda dapat menggunakan eksekusi kode dengan input multimodal dan hanya teks, tetapi respons akan selalu berupa teks atau kode saja.

Sebelum memulai

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Jika belum melakukannya, selesaikan panduan memulai, yang menjelaskan cara menyiapkan project Firebase, menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan backend untuk penyedia Gemini API yang Anda pilih, dan membuat instance GenerativeModel.

Untuk menguji dan melakukan iterasi pada perintah Anda, bahkan mendapatkan cuplikan kode yang dihasilkan, sebaiknya gunakan Google AI Studio.

Mengaktifkan eksekusi kode

Sebelum mencoba sampel ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi Anda.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang Anda pilih agar Anda dapat melihat konten khusus penyedia di halaman ini.

Saat membuat instance GenerativeModel, berikan CodeExecution sebagai alat yang dapat digunakan model untuk membuat responsnya. Hal ini memungkinkan model membuat dan menjalankan kode Python.

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [.codeExecution()]
)

let prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""

let response = try await model.generateContent(prompt)

guard let candidate = response.candidates.first else {
  print("No candidates in response.")
  return
}
for part in candidate.content.parts {
  if let textPart = part as? TextPart {
    print("Text = \(textPart.text)")
  } else if let executableCode = part as? ExecutableCodePart {
    print("Code = \(executableCode.code), Language = \(executableCode.language)")
  } else if let executionResult = part as? CodeExecutionResultPart {
    print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
  }
}

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools = listOf(Tool.codeExecution())
)

val prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."

val response = model.generateContent(prompt)

response.candidates.first().content.parts.forEach {
    if(it is TextPart) {
        println("Text = ${it.text}")
    }
    if(it is ExecutableCodePart) {
        println("Code = ${it.code}, Language = ${it.language}")
    }
    if(it is CodeExecutionResultPart) {
       println("Outcome = ${it.outcome}, Result = ${it.output}")
    }
}

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide code execution as a tool that the model can use to generate its response.
                        List.of(Tool.codeExecution()));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

String 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.";

Content prompt = new Content.Builder()
    .addText(text)
    .build();

ListenableFuture response = model.generateContent(prompt);

Futures.addCallback(response, new FutureCallback() {
   @Override
public void onSuccess(GenerateContentResponse response)   {
    // Access the first candidate's content parts
    List parts = response.getCandidates().get(0).getContent().getParts();
    for (Part part : parts) {
        if (part instanceof TextPart) {
            TextPart textPart = (TextPart) part;
            System.out.println("Text = " + textPart.getText());
        } else if (part instanceof ExecutableCodePart) {
            ExecutableCodePart codePart = (ExecutableCodePart) part;
            System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
        } else if (part instanceof CodeExecutionResultPart) {
            CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
            System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
        }
    }
}

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools: [{ codeExecution: {} }]
  }
);

const prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."

const result = await model.generateContent(prompt);
const response = await result.response;

const parts = response.candidates?.[0].content.parts;

if (parts) {
  parts.forEach((part) => {
    if (part.text) {
        console.log(`Text: ${part.text}`);
    } else if (part.executableCode) {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.codeExecutionResult) {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart

Dukungan untuk Flutter akan hadir di rilis berikutnya.

Unity

Dukungan untuk Unity akan tersedia di rilis berikutnya.

Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Menggunakan eksekusi kode dalam percakapan

Anda juga dapat menggunakan eksekusi kode sebagai bagian dari percakapan:

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [.codeExecution()]
)

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

let response = try await chat.sendMessage(prompt)

guard let candidate = response.candidates.first else {
  print("No candidates in response.")
  return
}
for part in candidate.content.parts {
  if let textPart = part as? TextPart {
    print("Text = \(textPart.text)")
  } else if let executableCode = part as? ExecutableCodePart {
    print("Code = \(executableCode.code), Language = \(executableCode.language)")
  } else if let executionResult = part as? CodeExecutionResultPart {
    print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
  }
}

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools = listOf(Tool.codeExecution())
)

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

response.candidates.first().content.parts.forEach {
    if(it is TextPart) {
        println("Text = ${it.text}")
    }
    if(it is ExecutableCodePart) {
        println("Code = ${it.code}, Language = ${it.language}")
    }
    if(it is CodeExecutionResultPart) {
       println("Outcome = ${it.outcome}, Result = ${it.output}")
    }
}

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide code execution as a tool that the model can use to generate its response.
                        List.of(Tool.codeExecution()));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
String 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.";

Content prompt = new Content.Builder()
    .addText(text)
    .build();

ChatFutures chat = model.startChat();
ListenableFuture response = chat.sendMessage(prompt);

Futures.addCallback(response, new FutureCallback() {
   @Override
public void onSuccess(GenerateContentResponse response)   {
    // Access the first candidate's content parts
    List parts = response.getCandidates().get(0).getContent().getParts();
    for (Part part : parts) {
        if (part instanceof TextPart) {
            TextPart textPart = (TextPart) part;
            System.out.println("Text = " + textPart.getText());
        } else if (part instanceof ExecutableCodePart) {
            ExecutableCodePart codePart = (ExecutableCodePart) part;
            System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
        } else if (part instanceof CodeExecutionResultPart) {
            CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
            System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
        }
    }
}

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools: [{ codeExecution: {} }]
  }
);

const prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."
const chat = model.startChat()
const result = await chat.sendMessage(prompt);
const response = await result.response;

const parts = response.candidates?.[0].content.parts;

if (parts) {
  parts.forEach((part) => {
    if (part.text) {
        console.log(`Text: ${part.text}`);
    } else if (part.executableCode) {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.codeExecutionResult) {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart

Dukungan untuk Flutter akan hadir di rilis berikutnya.

Unity

Dukungan untuk Unity akan tersedia di rilis berikutnya.

Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Harga

Tidak ada biaya tambahan untuk mengaktifkan eksekusi kode dan menyediakannya sebagai alat untuk model. Jika model memutuskan untuk menggunakan eksekusi kode, Anda akan ditagih dengan tarif token input dan output saat ini berdasarkan model Gemini yang Anda gunakan.

Diagram berikut menunjukkan model penagihan untuk eksekusi kode:

Diagram yang menunjukkan cara penagihan token saat model menggunakan eksekusi kode. 

Berikut ringkasan cara penagihan token saat model menggunakan eksekusi kode:

  • Perintah asli ditagih satu kali. Tokennya diberi label sebagai token perantara, yang ditagih sebagai token input.

  • Kode yang dihasilkan dan hasil kode yang dieksekusi ditagih seperti berikut:

    • Jika digunakan selama eksekusi kode, token tersebut akan diberi label sebagai token perantara yang ditagih sebagai token input.

    • Jika disertakan sebagai bagian dari respons akhir, token tersebut ditagih sebagai token output.

  • Ringkasan akhir dalam respons akhir ditagih sebagai token output.

Gemini API menyertakan jumlah token perantara dalam respons API, sehingga Anda mengetahui alasan Anda ditagih untuk token input di luar perintah awal Anda.

Perhatikan bahwa kode yang dihasilkan dapat mencakup output teks dan multimodal, seperti gambar.

Batasan dan praktik terbaik

  • Model hanya dapat membuat dan mengeksekusi kode Python. Fitur ini tidak dapat menampilkan artefak lain seperti file media.

  • Eksekusi kode dapat berjalan selama maksimal 30 detik sebelum waktu habis.

  • Dalam beberapa kasus, mengaktifkan eksekusi kode dapat menyebabkan regresi di area output model lainnya (misalnya, menulis cerita).

  • Alat eksekusi kode tidak mendukung URI file sebagai input/output. Namun, alat eksekusi kode mendukung input file dan output grafik sebagai byte inline. 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 hasil eksekusi kode. Jenis MIME yang didukung untuk byte inline adalah .cpp, .csv, .java, .jpeg, .js, .png, .py, .ts, dan .xml.

Library yang didukung

Lingkungan eksekusi kode mencakup library berikut. Anda tidak dapat menginstal library Anda sendiri.


Memberikan masukan tentang pengalaman Anda dengan Firebase AI Logic