Wykonanie kodu to narzędzie, które umożliwia modelowi generowanie i uruchamianie kodu w Pythonie. Model może uczyć się iteracyjnie na podstawie wyników wykonania kodu, aż uzyska ostateczne dane wyjściowe.
Możesz używać wykonywania kodu do tworzenia funkcji, które korzystają z rozumowania opartego na kodzie i generują dane wyjściowe w postaci tekstu. Możesz na przykład używać wykonywania kodu do rozwiązywania równań lub przetwarzania tekstu. Możesz też używać bibliotek dostępnych w środowisku wykonawczym kodu, aby wykonywać bardziej specjalistyczne zadania.
Podobnie jak w przypadku wszystkich narzędzi, które udostępniasz modelowi, to on decyduje, kiedy użyć wykonania kodu.
Porównanie wykonywania kodu z wywoływaniem funkcji
Wykonywanie kodu i wywoływanie funkcji to podobne funkcje. Ogólnie rzecz biorąc, jeśli model może obsłużyć Twój przypadek użycia, lepiej jest używać wykonywania kodu. Wykonywanie kodu jest też prostsze w użyciu, ponieważ wystarczy je włączyć.
Oto dodatkowe różnice między wykonywaniem kodu a wywoływaniem funkcji:
Wykonanie kodu | Wywoływanie funkcji |
---|---|
Użyj wykonywania kodu, jeśli chcesz, aby model napisał i uruchomił za Ciebie kod Pythona oraz zwrócił wynik. | Użyj wywoływania funkcji, jeśli masz już własne funkcje, które chcesz uruchamiać lokalnie. |
Wykonywanie kodu umożliwia modelowi uruchamianie kodu w backendzie interfejsu API w stałym, odizolowanym środowisku. | Wywoływanie funkcji umożliwia uruchamianie funkcji, o które prosi model, w dowolnym środowisku. |
Wykonanie kodu jest realizowane w ramach jednego żądania. Chociaż możesz opcjonalnie korzystać z wykonywania kodu w ramach funkcji czatu, nie jest to wymagane. | Wywoływanie funkcji wymaga dodatkowej prośby o odesłanie danych wyjściowych z każdego wywołania funkcji. Dlatego musisz korzystać z funkcji czatu. |
Obsługiwane modele
gemini-2.5-pro
gemini-2.5-flash
gemini-2.5-flash-lite
gemini-2.0-flash-001
(i jego automatycznie aktualizowany aliasgemini-2.0-flash
)gemini-2.0-flash-live-preview-04-09
Używanie wykonywania kodu
Wywoływanie kodu możesz stosować zarówno w przypadku danych wejściowych tylko tekstowych, jak i multimodalnych, ale odpowiedź będzie zawsze zawierać tylko tekst lub kod.
Zanim zaczniesz
Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod specyficzne dla tego dostawcy. |
Jeśli jeszcze tego nie zrobisz, zapoznaj się z przewodnikiem dla początkujących, w którym znajdziesz informacje o tym, jak skonfigurować projekt Firebase, połączyć aplikację z Firebase, dodać pakiet SDK, zainicjować usługę backendu dla wybranego dostawcy Gemini API i utworzyć instancję GenerativeModel
.
Do testowania i ulepszania promptów, a nawet uzyskiwania wygenerowanego fragmentu kodu zalecamy używanie Google AI Studio.
Włączanie wykonywania kodu
Zanim wypróbujesz ten przykład, zapoznaj się z sekcją Zanim zaczniesz w tym przewodniku, aby skonfigurować projekt i aplikację. W tej sekcji klikniesz też przycisk wybranego dostawcyGemini API, aby na tej stronie wyświetlały się treści dotyczące tego dostawcy. |
Podczas tworzenia instancji GenerativeModel
podaj CodeExecution
jako narzędzie, którego model może używać do generowania odpowiedzi. Dzięki temu model może generować i uruchamiać kod w Pythonie.
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
Obsługa Fluttera zostanie wprowadzona w następnej wersji.
Unity
Obsługa Unity zostanie wprowadzona w następnej wersji.
Dowiedz się, jak wybrać model odpowiednie do Twojego przypadku użycia i aplikacji.
Używanie wykonywania kodu na czacie
Możesz też używać wykonywania kodu w ramach czatu:
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
Obsługa Fluttera zostanie wprowadzona w następnej wersji.
Unity
Obsługa Unity zostanie wprowadzona w następnej wersji.
Dowiedz się, jak wybrać model odpowiednie do Twojego przypadku użycia i aplikacji.
Ceny
Włączenie wykonywania kodu i udostępnienie go jako narzędzia dla modelu nie wiąże się z żadnymi dodatkowymi opłatami. Jeśli model zdecyduje się na wykonanie kodu, opłata zostanie naliczona według aktualnej stawki za tokeny wejściowe i wyjściowe na podstawie używanego modelu Gemini.
Poniższy diagram przedstawia model rozliczeń za wykonywanie kodu:
Oto podsumowanie sposobu naliczania opłat za tokeny, gdy model korzysta z wykonywania kodu:
Pierwotny prompt jest rozliczany jednorazowo. Jego tokeny są oznaczane jako tokeny pośrednie, które są rozliczane jako tokeny wejściowe.
Wygenerowany kod i wynik wykonania kodu są rozliczane w ten sposób:
Gdy są używane podczas wykonywania kodu, są oznaczane jako tokeny pośrednie, za które naliczana jest opłata jak za tokeny wejściowe.
Gdy są one uwzględniane w odpowiedzi końcowej, są rozliczane jako tokeny wyjściowe.
Ostateczne podsumowanie w odpowiedzi końcowej jest rozliczane jako tokeny wyjściowe.
Gemini API zawiera w odpowiedzi API liczbę tokenów pośrednich, dzięki czemu wiesz, dlaczego naliczamy opłaty za tokeny wejściowe wykraczające poza początkowy prompt.
Pamiętaj, że wygenerowany kod może zawierać zarówno tekst, jak i dane wyjściowe multimodalne, np. obrazy.
Ograniczenia i sprawdzone metody
Model może tylko generować i uruchamiać kod Pythona. Nie może zwracać innych artefaktów, takich jak pliki multimedialne.
Wykonanie kodu może trwać maksymalnie 30 sekund, zanim upłynie limit czasu.
W niektórych przypadkach włączenie wykonywania kodu może prowadzić do regresji w innych obszarach danych wyjściowych modelu (np. w pisaniu opowiadań).
Narzędzie do wykonywania kodu nie obsługuje identyfikatorów URI plików jako danych wejściowych ani wyjściowych. Narzędzie do wykonywania kodu obsługuje jednak dane wejściowe w postaci plików i dane wyjściowe w postaci wykresów jako bajty wstawione w tekst. Korzystając z tych funkcji wejścia i wyjścia, możesz przesyłać pliki CSV i tekstowe, zadawać pytania dotyczące tych plików oraz generować wykresy Matplotlib w ramach wyniku wykonania kodu. Obsługiwane typy MIME dla bajtów wstawionych w tekście to
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
i.xml
.
Obsługiwane biblioteki
Środowisko wykonawcze kodu obejmuje te biblioteki: Nie możesz instalować własnych bibliotek.
Prześlij opinię o korzystaniu z usługi Firebase AI Logic