Thực thi mã là một công cụ cho phép mô hình tạo và chạy mã Python. Mô hình có thể học lặp đi lặp lại từ kết quả thực thi mã cho đến khi đạt được kết quả cuối cùng.
Bạn có thể sử dụng tính năng thực thi mã để xây dựng các tính năng có lợi từ hoạt động suy luận dựa trên mã và tạo đầu ra văn bản. Ví dụ: bạn có thể sử dụng tính năng thực thi mã để giải phương trình hoặc xử lý văn bản. Bạn cũng có thể dùng các thư viện có trong môi trường thực thi mã để thực hiện các tác vụ chuyên biệt hơn.
Giống như với tất cả các công cụ mà bạn cung cấp cho mô hình, mô hình sẽ quyết định thời điểm sử dụng tính năng thực thi mã.
So sánh giữa việc thực thi mã và gọi hàm
Việc thực thi mã và gọi hàm là các tính năng tương tự. Nhìn chung, bạn nên ưu tiên sử dụng tính năng thực thi mã nếu mô hình có thể xử lý trường hợp sử dụng của bạn. Việc thực thi mã cũng đơn giản hơn vì bạn chỉ cần bật tính năng này.
Sau đây là một số điểm khác biệt khác giữa việc thực thi mã và gọi hàm:
Thực thi mã | Gọi hàm |
---|---|
Sử dụng tính năng thực thi mã nếu bạn muốn mô hình viết và chạy mã Python cho bạn, sau đó trả về kết quả. | Sử dụng tính năng gọi hàm nếu bạn đã có các hàm riêng mà bạn muốn chạy cục bộ. |
Tính năng thực thi mã cho phép mô hình chạy mã trong phần phụ trợ API trong một môi trường cố định, biệt lập. | Tính năng gọi hàm cho phép bạn chạy các hàm mà mô hình yêu cầu trong bất kỳ môi trường nào bạn muốn. |
Quá trình thực thi mã sẽ được giải quyết trong một yêu cầu duy nhất. Mặc dù bạn có thể tuỳ ý sử dụng tính năng thực thi mã với khả năng trò chuyện, nhưng không bắt buộc. | Tính năng gọi hàm yêu cầu một yêu cầu bổ sung để gửi lại đầu ra từ mỗi lệnh gọi hàm. Do đó, bạn phải sử dụng tính năng trò chuyện. |
Các mô hình được hỗ trợ
gemini-2.5-pro
gemini-2.5-flash
gemini-2.5-flash-lite
gemini-2.0-flash-001
(và bí danh được cập nhật tự động của miền này làgemini-2.0-flash
)gemini-2.0-flash-live-preview-04-09
Sử dụng tính năng thực thi mã
Bạn có thể sử dụng tính năng thực thi mã với cả dữ liệu đầu vào chỉ bằng văn bản và dữ liệu đầu vào đa phương thức, nhưng phản hồi sẽ luôn chỉ là văn bản hoặc mã.
Trước khi bắt đầu
Nhấp vào nhà cung cấp Gemini API để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Nếu bạn chưa thực hiện, hãy hoàn tất hướng dẫn bắt đầu sử dụng. Hướng dẫn này mô tả cách thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK, khởi chạy dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và tạo một phiên bản GenerativeModel
.
Để kiểm thử và lặp lại các câu lệnh, thậm chí nhận được một đoạn mã được tạo, bạn nên sử dụng Google AI Studio.
Bật tính năng thực thi mã
Trước khi dùng thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Khi bạn tạo phiên bản GenerativeModel
, hãy cung cấp CodeExecution
làm công cụ mà mô hình có thể dùng để tạo câu trả lời. Nhờ đó, mô hình có thể tạo và chạy mã 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
Chúng tôi sẽ hỗ trợ Flutter trong bản phát hành tiếp theo.
Unity
Chúng tôi sẽ hỗ trợ Unity trong bản phát hành tiếp theo.
Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.
Sử dụng tính năng thực thi mã trong cuộc trò chuyện
Bạn cũng có thể sử dụng tính năng thực thi mã trong cuộc trò chuyện:
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
Chúng tôi sẽ hỗ trợ Flutter trong bản phát hành tiếp theo.
Unity
Chúng tôi sẽ hỗ trợ Unity trong bản phát hành tiếp theo.
Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.
Giá
Bạn không phải trả thêm phí khi bật tính năng thực thi mã và cung cấp tính năng này dưới dạng một công cụ cho mô hình. Nếu mô hình quyết định sử dụng tính năng thực thi mã, thì bạn sẽ bị tính phí theo mức giá hiện tại của mã thông báo đầu vào và đầu ra dựa trên mô hình Gemini mà bạn đang sử dụng.
Sơ đồ sau đây cho thấy mô hình thanh toán cho việc thực thi mã:
Sau đây là thông tin tóm tắt về cách tính phí mã thông báo khi một mô hình sử dụng tính năng thực thi mã:
Câu lệnh ban đầu chỉ bị tính phí một lần. Các mã thông báo của mô hình này được gắn nhãn là mã thông báo trung gian và được tính phí dưới dạng mã thông báo đầu vào.
Mã được tạo và kết quả của mã đã thực thi được tính phí như sau:
Khi được dùng trong quá trình thực thi mã, các mã này được gắn nhãn là mã thông báo trung gian và được tính phí là mã thông báo đầu vào.
Khi được đưa vào phản hồi cuối cùng, các mã thông báo này sẽ được tính phí dưới dạng mã thông báo đầu ra.
Bản tóm tắt cuối cùng trong phản hồi cuối cùng được tính phí dưới dạng mã thông báo đầu ra.
Gemini API bao gồm số lượng mã thông báo trung gian trong phản hồi API, nhờ đó, bạn biết được lý do bạn bị tính phí cho mã thông báo đầu vào ngoài câu lệnh ban đầu.
Xin lưu ý rằng mã được tạo có thể bao gồm cả văn bản và đầu ra đa phương thức, chẳng hạn như hình ảnh.
Giới hạn và các phương pháp hay nhất
Mô hình này chỉ có thể tạo và thực thi mã Python. Phương thức này không thể trả về các cấu phần phần mềm khác, chẳng hạn như tệp nội dung nghe nhìn.
Thời gian thực thi mã có thể chạy tối đa 30 giây trước khi hết thời gian chờ.
Trong một số trường hợp, việc cho phép thực thi mã có thể dẫn đến sự hồi quy ở các khía cạnh khác của đầu ra mô hình (ví dụ: viết một câu chuyện).
Công cụ thực thi mã không hỗ trợ URI tệp làm dữ liệu đầu vào/đầu ra. Tuy nhiên, công cụ thực thi mã hỗ trợ đầu vào tệp và đầu ra biểu đồ dưới dạng các byte nội tuyến. Bằng cách sử dụng các chức năng đầu vào và đầu ra này, bạn có thể tải tệp CSV và tệp văn bản lên, đặt câu hỏi về các tệp đó và tạo biểu đồ Matplotlib trong kết quả thực thi mã. Các loại mime được hỗ trợ cho các byte nội tuyến là
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
và.xml
.
Các thư viện được hỗ trợ
Môi trường thực thi mã bao gồm các thư viện sau. Bạn không thể cài đặt thư viện của riêng mình.
Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic