Выполнение кода — это инструмент, позволяющий модели генерировать и запускать код Python. Модель может итеративно обучаться на основе результатов выполнения кода, пока не достигнет конечного результата.
Вы можете использовать выполнение кода для создания функций, использующих рассуждения на основе кода и генерирующих текстовый вывод. Например, выполнение кода можно использовать для решения уравнений или обработки текста. Вы также можете использовать библиотеки, входящие в среду выполнения кода, для выполнения более специализированных задач.
Как и в случае со всеми инструментами, которые вы предоставляете модели, модель сама решает, когда использовать выполнение кода.
Сравнение выполнения кода и вызова функции
Выполнение кода и вызов функций — схожие функции. В общем случае, если модель подходит для вашего случая, предпочтительнее использовать выполнение кода. Выполнение кода также проще в использовании, поскольку вы просто включаете его.
Вот некоторые дополнительные различия между выполнением кода и вызовом функций:
Выполнение кода | Вызов функции |
---|---|
Используйте выполнение кода, если вы хотите, чтобы модель написала и запустила код Python для вас и вернула результат. | Используйте вызов функций, если у вас уже есть собственные функции, которые вы хотите запустить локально. |
Выполнение кода позволяет модели запускать код в бэкэнде API в фиксированной изолированной среде. | Вызов функций позволяет вам запускать функции, запрашиваемые моделью, в любой желаемой вами среде. |
Выполнение кода выполняется одним запросом. Хотя вы можете использовать выполнение кода с функцией чата, это не является обязательным требованием. | Вызов функции требует дополнительного запроса на отправку результата каждого вызова функции. Поэтому необходимо использовать функцию чата. |
Поддерживаемые модели
-
gemini-2.5-pro
-
gemini-2.5-flash
-
gemini-2.5-flash-lite
-
gemini-2.0-flash-001
(и его автоматически обновляемый псевдонимgemini-2.0-flash
) -
gemini-2.0-flash-live-preview-04-09
Использовать выполнение кода
Вы можете использовать выполнение кода как с текстовым, так и с многомодальным вводом, но ответом всегда будет только текст или код.
Прежде чем начать
Щелкните своего поставщика API Gemini , чтобы просмотреть специфичный для этого поставщика контент и код на этой странице. |
Если вы еще этого не сделали, ознакомьтесь с руководством по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать внутреннюю службу для выбранного поставщика API Gemini и создать экземпляр GenerativeModel
.
Включить выполнение кода
Прежде чем приступить к работе с этим примером, выполните указания раздела «Перед началом работы» данного руководства, чтобы настроить свой проект и приложение. В этом разделе вы также нажмете кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, специфичный для этого поставщика . |
При создании экземпляра GenerativeModel
предоставьте CodeExecution
в качестве инструмента, который модель сможет использовать для генерации ответа. Это позволит модели генерировать и запускать код Python.
Быстрый
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 появится в следующей версии.
Единство
Поддержка Unity появится в следующей версии.
Узнайте, как выбрать модельподходящий для вашего варианта использования и приложения.
Вывод может выглядеть примерно так (он отформатирован для удобства чтения):
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.
Этот вывод объединяет несколько частей контента, которые модель возвращает при использовании выполнения кода:
-
text
: Встроенный текст, сгенерированный моделью -
executableCode
: Код, сгенерированный моделью, который предназначен для выполнения. -
codeExecutionResult
: Результат выполненного кода
Соглашения об именовании этих частей различаются в зависимости от языка программирования.
Использовать выполнение кода в чате
Вы также можете использовать выполнение кода в рамках чата:
Быстрый
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 появится в следующей версии.
Единство
Поддержка Unity появится в следующей версии.
Узнайте, как выбрать модельподходящий для вашего варианта использования и приложения.
Цены
Дополнительная плата за включение функции выполнения кода и предоставление её в качестве инструмента для модели не взимается. Если модель решит использовать функцию выполнения кода, с вас будет взиматься плата по текущему тарифу на входные и выходные токены в зависимости от используемой вами модели Gemini.
На следующей диаграмме показана модель выставления счетов за выполнение кода:
Ниже приведено краткое описание того, как начисляются токены, когда модель использует выполнение кода:
Исходное приглашение оплачивается один раз. Его токены помечаются как промежуточные токены, которые оплачиваются как входные токены .
Сгенерированный код и результат выполненного кода выставляются следующим образом:
Когда они используются во время выполнения кода, они помечаются как промежуточные токены, которые тарифицируются как входные токены .
Когда они включены как часть окончательного ответа, они выставляются в счет как выходные токены .
Окончательное резюме в окончательном ответе учитывается как выходные токены .
API Gemini включает промежуточное количество токенов в ответе API, поэтому вы знаете, почему с вас взимается плата за входные токены сверх первоначального запроса.
Обратите внимание, что сгенерированный код может включать как текст, так и многомодальные выходные данные, такие как изображения.
Ограничения и передовой опыт
Модель может генерировать и выполнять только код Python. Она не может возвращать другие артефакты, например медиафайлы.
Выполнение кода может длиться не более 30 секунд, после чего истечет время ожидания.
В некоторых случаях включение выполнения кода может привести к регрессиям в других областях вывода модели (например, написание истории).
Инструмент выполнения кода не поддерживает файловые URI в качестве входных и выходных данных. Однако инструмент выполнения кода поддерживает файловый ввод и вывод графиков в виде встроенных байтов. Используя эти возможности ввода и вывода, вы можете загружать CSV-файлы и текстовые файлы, задавать вопросы о файлах и получать графики Matplotlib, генерируемые в результате выполнения кода. Поддерживаемые MIME-типы для встроенных байтов:
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
и.xml
.
Поддерживаемые библиотеки
Среда выполнения кода включает следующие библиотеки. Установка собственных библиотек невозможна.
- атрибуты
- шахматы
- контурный
- fpdf
- геопанды
- imageio
- jinja2
- joblib
- jsonschema
- jsonschema-спецификации
- lxml
- matplotlib
- mpmath
- numpy
- opencv-python
- openpyxl
- упаковка
- панды
- подушка
- протобуф
- пилатекс
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- reportlab
- scikit-learn
- сципи
- морское рождение
- шесть
- striprtf
- симпи
- табулировать
- тензорный поток
- инструменты
- xlrd
- Альтаир
- Шахматы
- Cv2
- Matplotlib
- Мпматематика
- NumPy
- Панды
- PDFminer
- Reportlab
- Сиборн
- Склеарн
- Статмодели
- Striprtf
- SymPy
- Табулировать
Оставьте отзыв о своем опыте работы с Firebase AI Logic