اجرای کد ابزاری است که مدل را قادر می سازد کد پایتون را تولید و اجرا کند. مدل می تواند به طور مکرر از نتایج اجرای کد یاد بگیرد تا زمانی که به خروجی نهایی برسد.
میتوانید از اجرای کد برای ساخت ویژگیهایی استفاده کنید که از استدلال مبتنی بر کد بهره میبرند و خروجی متن تولید میکنند. به عنوان مثال، می توانید از اجرای کد برای حل معادلات یا پردازش متن استفاده کنید. همچنین می توانید از کتابخانه های موجود در محیط اجرای کد برای انجام کارهای تخصصی تر استفاده کنید.
درست مانند تمام ابزارهایی که در اختیار مدل قرار می دهید، مدل تصمیم می گیرد که چه زمانی از اجرای کد استفاده کند.
مقایسه اجرای کد در مقابل فراخوانی تابع
اجرای کد و فراخوانی تابع ویژگی های مشابهی هستند. به طور کلی، در صورتی که مدل می تواند مورد استفاده شما را مدیریت کند، بهتر است از اجرای کد استفاده کنید. اجرای کد نیز برای استفاده ساده تر است زیرا فقط آن را فعال می کنید.
در اینجا چند تفاوت اضافی بین اجرای کد و فراخوانی تابع وجود دارد:
اجرای کد | فراخوانی تابع |
---|---|
اگر می خواهید مدل برای شما کد پایتون بنویسد و اجرا کند و نتیجه را برگرداند، از اجرای کد استفاده کنید. | اگر از قبل توابع خود را دارید که می خواهید به صورت محلی اجرا کنید، از فراخوانی تابع استفاده کنید. |
اجرای کد به مدل اجازه می دهد تا کد را در باطن 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 را اضافه کنید، سرویس Backend را برای ارائهدهنده API Gemini انتخابی خود مقداردهی کنید و یک نمونه GenerativeModel
ایجاد کنید.
اجرای کد را فعال کنید
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
هنگامی که نمونه GenerativeModel
را ایجاد می کنید، CodeExecution
به عنوان ابزاری ارائه کنید که مدل می تواند از آن برای تولید پاسخ خود استفاده کند. این به مدل اجازه می دهد تا کد پایتون را تولید و اجرا کند.
سویفت
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 که استفاده میکنید، صورتحساب شما با نرخ فعلی نشانههای ورودی و خروجی محاسبه میشود.
نمودار زیر مدل صورتحساب برای اجرای کد را نشان می دهد:
در اینجا خلاصه ای از نحوه صورتحساب توکن ها در زمانی که یک مدل از اجرای کد استفاده می کند آورده شده است:
درخواست اصلی یک بار صورتحساب می شود. توکنهای آن بهعنوان توکنهای میانی برچسبگذاری میشوند که بهعنوان نشانههای ورودی صورتحساب میشوند.
کد تولید شده و نتیجه کد اجرا شده به صورت زیر محاسبه می شود:
هنگامی که آنها در طول اجرای کد استفاده می شوند - آنها به عنوان توکن های میانی برچسب گذاری می شوند که به عنوان نشانه های ورودی صورتحساب می شوند.
هنگامی که آنها به عنوان بخشی از پاسخ نهایی گنجانده می شوند - آنها به عنوان نشانه های خروجی صورتحساب می شوند.
خلاصه نهایی در پاسخ نهایی به عنوان نشانه های خروجی صورتحساب می شود.
Gemini API شامل یک تعداد توکن میانی در پاسخ API است، بنابراین میدانید که چرا برای نشانههای ورودی فراتر از درخواست اولیهتان هزینه دریافت میکنید.
توجه داشته باشید که کد تولید شده می تواند هم متن و هم خروجی های چندوجهی مانند تصاویر را شامل شود.
محدودیت ها و بهترین شیوه ها
مدل فقط می تواند کد پایتون را تولید و اجرا کند. نمی تواند مصنوعات دیگر مانند فایل های رسانه ای را برگرداند.
اجرای کد می تواند حداکثر 30 ثانیه قبل از اتمام زمان اجرا شود.
در برخی موارد، فعال کردن اجرای کد میتواند منجر به رگرسیون در سایر حوزههای خروجی مدل شود (مثلاً نوشتن یک داستان).
ابزار اجرای کد URI فایل را به عنوان ورودی/خروجی پشتیبانی نمی کند. با این حال، ابزار اجرای کد از ورودی فایل و خروجی نمودار به صورت بایت های خطی پشتیبانی می کند. با استفاده از این قابلیتهای ورودی و خروجی، میتوانید فایلهای CSV و متنی را آپلود کنید، درباره فایلها سؤال بپرسید و نمودارهای Matplotlib را به عنوان بخشی از نتیجه اجرای کد تولید کنید. انواع mime پشتیبانی شده برای بایت های درون خطی عبارتند از
.cpp
،.csv
،.java
،.jpeg
،.js
،.png
،.py
،.ts
، و.xml
.
کتابخانه های پشتیبانی شده
محیط اجرای کد شامل کتابخانه های زیر می باشد. شما نمی توانید کتابخانه های خود را نصب کنید.
- attrs
- شطرنج
- کانتورپی
- fpdf
- ژئوپاندها
- imageio
- jinja2
- joblib
- jsonschema
- مشخصات jsonschema
- lxml
- matplotlib
- mpmath
- بی حسی
- opencv-python
- openpyxl
- بسته بندی
- پانداها
- بالش
- پروتوباف
- پیلاتکس
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- گزارش آزمایشگاه
- scikit-یادگیری
- تند
- متولد دریا
- شش
- striptf
- دلسوز
- جدول بندی
- تنسورفلو
- toolz
- xlrd
- الطیر
- شطرنج
- Cv2
- Matplotlib
- Mpmath
- NumPy
- پانداها
- پی دی اف ماینر
- Reportlab
- متولد دریا
- Sklearn
- مدل های آماری
- Striprtf
- SymPy
- جدول
درباره تجربه خود با Firebase AI Logic بازخورد بدهید