Kod yürütme, modelin Python kodu oluşturup çalıştırmasını sağlayan bir araçtır. Model, 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ı muhakemeden yararlanan ve metin çıkışı oluşturan özellikler geliştirebilirsiniz. Örneğin, denklemleri çözmek veya metinleri işlemek için kod yürütme özelliğini kullanabilirsiniz. Daha özel görevleri gerçekleştirmek için kod yürütme ortamında yer alan kitaplıkları da kullanabilirsiniz.
Modele sağladığınız tüm araçlarda olduğu gibi, kod yürütmenin ne zaman kullanılacağına model karar verir.
Kod yürütme ile işlev çağrısı karşılaştırması
Kod yürütme ve işlev çağırma benzer özelliklerdir. Genel olarak, model kullanım alanınızı işleyebiliyorsa kod yürütmeyi tercih etmelisiniz. Kod yürütme de yalnızca etkinleştirmeniz gerektiğinden daha kolay kullanılır.
Kod yürütme ve işlev çağırma arasındaki bazı ek farklar şunlardır:
Kod yürütme | İşlev çağırma |
---|---|
Modelin sizin için Python kodu yazıp çalıştırmasını ve sonucu döndürmesini istiyorsanız kod yürütmeyi kullanın. | Yerel olarak çalıştırmak istediğiniz kendi işlevleriniz varsa işlev çağrısını kullanın. |
Kod yürütme, modelin API arka ucunda kodu sabit ve ayrı bir ortamda çalıştırmasına olanak tanır. | İşlev çağrısı, modelin istediği işlevleri istediğiniz ortamda çalıştırmanıza olanak tanır. |
Kod yürütme tek bir istekle çözülür. Sohbet özelliğiyle kod yürütmeyi isteğe bağlı olarak kullanabilirsiniz ancak bu zorunlu değildir. | İşlev çağrısı, her işlev çağrısından gelen çıkışı geri göndermek için ek bir istek gerektirir. Bu nedenle, sohbet özelliğini kullanmanız gerekir. |
Desteklenen modeller
gemini-2.5-pro
gemini-2.5-flash
gemini-2.5-flash-lite
gemini-2.0-flash-001
(ve otomatik olarak güncellenen diğer adıgemini-2.0-flash
)gemini-2.0-flash-live-preview-04-09
Kod yürütmeyi kullanma
Kod yürütme özelliğini yalnızca metin içeren ve çok formatlı girişlerle kullanabilirsiniz ancak yanıt her zaman yalnızca metin veya kod şeklinde olur.
Başlamadan önce
Bu sayfada sağlayıcıya özel içerikleri ve kodu görüntülemek için Gemini API sağlayıcınızı tıklayın. |
Henüz yapmadıysanız başlangıç kılavuzunu tamamlayın. Bu kılavuzda Firebase projenizi ayarlama, uygulamanızı Firebase'e bağlama, SDK'yı ekleme, seçtiğiniz Gemini API sağlayıcısı için arka uç hizmetini başlatma ve GenerativeModel
örneği oluşturma hakkında bilgiler yer alır.
İstemlerinizi test etmek ve yinelemek, hatta oluşturulmuş bir kod snippet'i almak için Google AI Studio'ı kullanmanızı öneririz.
Kod yürütmeyi etkinleştirme
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
GenerativeModel
örneğini oluştururken CodeExecution
değerini, modelin yanıtını oluşturmak için kullanabileceği bir araç olarak sağlayın. Bu sayede model, Python kodu oluşturup çalıştırabilir.
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
Flutter desteği, bir sonraki sürümde kullanıma sunulacaktır.
Unity
Unity desteği, bir sonraki sürümde kullanıma sunulacak.
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
Sohbette kod yürütme özelliğini kullanma
Kod yürütmeyi sohbetin bir parçası olarak da kullanabilirsiniz:
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
Flutter desteği, bir sonraki sürümde kullanıma sunulacaktır.
Unity
Unity desteği, bir sonraki sürümde kullanıma sunulacak.
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
Fiyatlandırma
Kod yürütmeyi etkinleştirmenin ve bunu modele araç olarak sunmanın ek bir maliyeti yoktur. Model, kod yürütmeyi kullanmaya karar verirse kullandığınız Gemini modeline göre giriş ve çıkış jetonlarının mevcut ücreti üzerinden faturalandırılırsınız.
Aşağıdaki şemada kod yürütme için faturalandırma modeli gösterilmektedir:
Bir model kod yürütmeyi kullandığında jetonların nasıl faturalandırıldığıyla ilgili özeti aşağıda bulabilirsiniz:
Orijinal istem bir kez faturalandırılır. Bu modelin jetonları, giriş jetonları olarak faturalandırılan ara jetonları olarak etiketlenir.
Oluşturulan kod ve yürütülen kodun sonucu aşağıdaki şekilde faturalandırılır:
Kod yürütme sırasında kullanıldıklarında ara jetonları olarak etiketlenirler ve giriş jetonları olarak faturalandırılırlar.
Son yanıta dahil edildiklerinde çıkış jetonları olarak faturalandırılır.
Son yanıttaki nihai özet, çıkış jetonları olarak faturalandırılır.
Gemini API, API yanıtında ara jeton sayısını içerir. Böylece, ilk isteminizin ötesindeki giriş jetonları için neden ücretlendirildiğinizi bilirsiniz.
Oluşturulan kodun hem metin hem de resim gibi çok formatlı çıktılar içerebileceğini unutmayın.
Sınırlamalar ve en iyi uygulamalar
Model yalnızca Python kodu oluşturabilir ve yürütebilir. Medya dosyaları gibi diğer öğeler geri döndürülemez.
Kod yürütme, zaman aşımına uğramadan önce en fazla 30 saniye çalışabilir.
Bazı durumlarda, kod yürütmenin etkinleştirilmesi model çıktısının diğer alanlarında (ör. hikaye yazma) gerilemelere yol açabilir.
Kod yürütme aracı, giriş/çıkış olarak dosya URI'lerini desteklemez. Ancak kod yürütme aracı, dosya girişini ve grafik çıkışını satır içi bayt olarak destekler. Bu giriş ve çıkış özelliklerini kullanarak CSV ve metin dosyalarını yükleyebilir, dosyalarla ilgili sorular sorabilir ve kod yürütme sonucunun bir parçası olarak Matplotlib grafikleri oluşturabilirsiniz. Satır içi baytlar için desteklenen MIME türleri şunlardır:
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
ve.xml
.
Desteklenen kitaplıklar
Kod yürütme ortamı aşağıdaki kitaplıkları içerir. Kendi kitaplıklarınızı yükleyemezsiniz.
Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirim verme