הכלי 'הרצת קוד' מאפשר למודל ליצור ולהריץ קוד 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
שימוש בהרצת קוד
אפשר להשתמש בהרצת קוד גם עם קלט טקסט בלבד וגם עם קלט רב-אופנים, אבל התשובה תמיד תהיה טקסט או קוד בלבד.
לפני שמתחילים
לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק. |
אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה, שבו מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות ה-Backend עבור ספק Gemini API שבחרתם וליצור מופע GenerativeModel
.
כדי לבדוק את ההנחיות ולשפר אותן, ואפילו לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.
הפעלת ביצוע קוד
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שמפורטים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה, צריך גם ללחוץ על לחצן של ספק Gemini API שבחרתם כדי שיוצג בדף הזה תוכן שספציפי לספק. |
כשיוצרים את מופע GenerativeModel
, מציינים את CodeExecution
ככלי שהמודל יכול להשתמש בו כדי ליצור את התשובה. כך המודל יכול ליצור ולהריץ קוד 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
התמיכה ב-Flutter תתווסף בגרסה הבאה.
Unity
התמיכה ב-Unity תהיה זמינה בגרסה הבאה.
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה.
איך משתמשים בהרצת קוד בשיחה
אפשר גם להשתמש בהרצת קוד כחלק משיחה:
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 תתווסף בגרסה הבאה.
Unity
התמיכה ב-Unity תהיה זמינה בגרסה הבאה.
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה.
תמחור
אין חיוב נוסף על הפעלת קוד ועל מתן הקוד ככלי למודל. אם המודל מחליט להשתמש בהרצת קוד, תחויבו לפי התעריף הנוכחי של טוקנים של קלט ופלט על סמך מודל Gemini שבו אתם משתמשים.
בתרשים הבא מוצג מודל החיוב על ביצוע קוד:
הנה סיכום של אופן החיוב על אסימונים כשמשתמשים במודל עם הרצת קוד:
החיוב על ההנחיה המקורית מתבצע פעם אחת. האסימונים שלו מסומנים כאסימונים ביניים, והחיוב עליהם הוא כאסימוני קלט.
החיוב על הקוד שנוצר ועל התוצאה של הקוד שהופעל מתבצע באופן הבא:
כשמשתמשים בהם במהלך הרצת הקוד – הם מסומנים כאסימונים ביניים ומחויבים כאסימוני קלט.
אם הם נכללים בתשובה הסופית, הם מחויבים כטוקנים של פלט.
הסיכום הסופי בתשובה הסופית מחויב כטוקנים של פלט.
התגובה של ה-API כוללת את מספר האסימונים הביניים Gemini API, כך שתוכלו לדעת למה אתם מחויבים על אסימוני קלט מעבר להנחיה הראשונית.
שימו לב שהקוד שנוצר יכול לכלול גם טקסט וגם פלט מולטימודאלי, כמו תמונות.
מגבלות ושיטות מומלצות
המודל יכול רק ליצור ולהריץ קוד Python. הוא לא יכול להחזיר פריטים אחרים כמו קובצי מדיה.
הביצוע של הקוד יכול להימשך עד 30 שניות לפני שחלף הזמן הקצוב לתפוגה.
במקרים מסוימים, הפעלת ביצוע הקוד עלולה לגרום לרגרסיות בתחומים אחרים של פלט המודל (לדוגמה, כתיבת סיפור).
הכלי להרצת קוד לא תומך בכתובות URI של קבצים כקלט או כפלט. עם זאת, כלי ההרצה של הקוד תומך בקלט של קבצים ובפלט של גרפים כבייטים מוטבעים. באמצעות היכולות האלה של קלט ופלט, אתם יכולים להעלות קובצי CSV וקובצי טקסט, לשאול שאלות לגבי הקבצים ולקבל גרפים של Matplotlib שנוצרים כחלק מתוצאת ההרצה של הקוד. סוגי ה-MIME הנתמכים עבור בייטים מוטבעים הם
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
ו-.xml
.
ספריות נתמכות
סביבת ההפעלה של הקוד כוללת את הספריות הבאות. אי אפשר להתקין ספריות משלכם.
רוצה לתת משוב על חוויית השימוש ב-Firebase AI Logic?