تنفيذ الرمز البرمجي

"تنفيذ الرموز البرمجية" هي أداة تتيح للنموذج إنشاء رموز Python البرمجية وتنفيذها. ويمكن للنموذج أن يتعلّم بشكل متكرّر من نتائج تنفيذ الرموز البرمجية إلى أن يصل إلى النتيجة النهائية.

يمكنك استخدام ميزة تنفيذ الرموز البرمجية لإنشاء ميزات تستفيد من الاستدلال المستند إلى الرموز البرمجية وتُنشئ نصوصًا. على سبيل المثال، يمكنك استخدام ميزة تنفيذ الرموز البرمجية لحل المعادلات أو معالجة النصوص. يمكنك أيضًا استخدام المكتبات المضمّنة في بيئة تنفيذ الرموز البرمجية لإجراء مهام أكثر تخصّصًا.

كما هو الحال مع جميع الأدوات التي تقدّمها للنموذج، يقرّر النموذج متى يستخدم ميزة تنفيذ الرموز البرمجية.

الانتقال إلى تنفيذ الرمز

مقارنة بين ميزتَي تنفيذ الرموز البرمجية واستدعاء الدوال

تطبيق الرموز البرمجية واستدعاء الدوال هما ميزتان متشابهتان. بشكل عام، من الأفضل استخدام ميزة تنفيذ الرموز البرمجية إذا كان النموذج قادرًا على التعامل مع حالة الاستخدام. كما أنّ استخدام ميزة تنفيذ الرموز البرمجية أسهل، لأنّك تحتاج فقط إلى تفعيلها.

في ما يلي بعض الاختلافات الإضافية بين ميزتَي تنفيذ الرموز البرمجية واستدعاء الدوال:

تطبيق الرموز البرمجية استدعاء الدالة
يمكنك استخدام ميزة تنفيذ الرموز البرمجية إذا أردت أن يكتب النموذج رمز Python برمجيًا ويشغّله نيابةً عنك ويعرض النتيجة. استخدِم ميزة "استدعاء الدوال" إذا كانت لديك دوال خاصة بك تريد تشغيلها محليًا.
تتيح ميزة تنفيذ الرموز البرمجية للنموذج تشغيل الرموز البرمجية في الخلفية الخاصة بواجهة برمجة التطبيقات في بيئة ثابتة ومعزولة. تتيح لك ميزة "استدعاء الدوال" تنفيذ الدوال التي يطلبها النموذج في أي بيئة تريدها.
يتم حلّ مشكلة تنفيذ الرموز البرمجية في طلب واحد. ومع أنّه يمكنك استخدام ميزة تنفيذ الرموز البرمجية مع ميزة المحادثة، ليس عليك فعل ذلك. يتطلّب استدعاء الدوال إرسال طلب إضافي لإرجاع الناتج من كل استدعاء دالة. لذلك، عليك استخدام ميزة المحادثة.

النماذج المتوافقة

  • gemini-4-argon
  • ‫gemini-3.8-flash (والإصدارات الأقدم gemini-3.7-flash وgemini-3.6-flash وgemini-3.5-flash)
  • ‫gemini-3.5-flash-lite (والإصدار الأقدم gemini-3.1-flash-lite)

يتيح أيضًا نموذج gemini-3.1-pro-preview ونموذج Gemini 2.5 للاستخدام العام (اللذان تم إيقافهما نهائيًا) هذه الإمكانية.

استخدام ميزة "تطبيق الرموز البرمجية"

يمكنك استخدام ميزة تنفيذ الرموز البرمجية مع كل من الإدخال النصي فقط والإدخال المتعدد الوسائط، ولكن الرد سيكون دائمًا نصًا أو رمزًا برمجيًا فقط.

قبل البدء

انقر على مزوّد خدمة Gemini API لعرض المحتوى والرمز البرمجي الخاصَّين بالمزوّد على هذه الصفحة.

إذا لم يسبق لك إجراء ذلك، أكمِل دليل البدء الذي يوضّح كيفية إعداد مشروعك على Firebase وربط تطبيقك بمنصة Firebase وإضافة حزمة تطوير البرامج (SDK) وإعداد خدمة الخلفية لمقدّم خدمة Gemini API الذي اخترته وإنشاء مثيل GenerativeModel.

لاختبار الطلبات وتحسينها، ننصحك باستخدام Google AI Studio.

تفعيل ميزة "تطبيق الرموز البرمجية"

قبل تجربة هذا النموذج، أكمِل قسم قبل البدء من هذا الدليل لإعداد مشروعك وتطبيقك.
في هذا القسم، ستنقر أيضًا على زر لمقدّم الخدمة Gemini API الذي اخترته حتى يظهر لك المحتوى الخاص بمقدّم الخدمة في هذه الصفحة.

عند إنشاء مثيل GenerativeModel، قدِّم CodeExecution كأداة يمكن للنموذج استخدامها لإنشاء ردّه. يتيح ذلك للنموذج إنشاء رمز Python وتشغيله.

Swift


import FirebaseAILogic

// 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.type === "text") {
      console.log(`Text: ${part.text}`);
    } else if (part.type === "executableCode") {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.type === "codeExecutionResult") {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [
    Tool.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.';

final response = await model.generateContent([Content.text(prompt)]);

final buffer = StringBuffer();
    for (final part in response.candidates.first.content.parts) {
      if (part is TextPart) {
        buffer.writeln(part.text);
      } else if (part is ExecutableCodePart) {
        buffer.writeln('Executable Code:');
        buffer.writeln('Language: ${part.language}');
        buffer.writeln('Code:');
        buffer.writeln(part.code);
      } else if (part is CodeExecutionResultPart) {
        buffer.writeln('Code Execution Result:');
        buffer.writeln('Outcome: ${part.outcome}');
        buffer.writeln('Output:');
        buffer.writeln(part.output);
      }
    }

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: new Tool[] { new Tool(new CodeExecution()) }
);

var 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.";

var response = await model.GenerateContentAsync(prompt);

foreach (var part in response.Candidates.First().Content.Parts) {
  if (part is ModelContent.TextPart tp) {
    UnityEngine.Debug.Log($"Text = {tp.Text}");
  } else if (part is ModelContent.ExecutableCodePart esp) {
    UnityEngine.Debug.Log($"Code = {esp.Code}, Language = {esp.Language}");
  } else if (part is ModelContent.CodeExecutionResultPart cerp) {
    UnityEngine.Debug.Log($"Outcome = {cerp.Outcome}, Output = {cerp.Output}");
  }
}

تعرَّف على كيفية اختيار نموذج مناسبَين لحالة الاستخدام والتطبيق.

استخدام ميزة "تنفيذ الرموز البرمجية" في المحادثة

يمكنك أيضًا استخدام ميزة تنفيذ الرموز البرمجية كجزء من محادثة:

Swift


import FirebaseAILogic

// 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 parts = result.response.candidates?.[0].content.parts;

if (parts) {
  parts.forEach((part) => {
    if (part.type === "text") {
      console.log(`Text: ${part.text}`);
    } else if (part.type === "executableCode") {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.type === "codeExecutionResult") {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [
    Tool.codeExecution(),
  ],
);

final codeExecutionChat = await model.startChat();

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.';
final response = await codeExecutionChat.sendMessage(Content.text(prompt));

final buffer = StringBuffer();
    for (final part in response.candidates.first.content.parts) {
      if (part is TextPart) {
        buffer.writeln(part.text);
      } else if (part is ExecutableCodePart) {
        buffer.writeln('Executable Code:');
        buffer.writeln('Language: ${part.language}');
        buffer.writeln('Code:');
        buffer.writeln(part.code);
      } else if (part is CodeExecutionResultPart) {
        buffer.writeln('Code Execution Result:');
        buffer.writeln('Outcome: ${part.outcome}');
        buffer.writeln('Output:');
        buffer.writeln(part.output);
      }
    }

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: new Tool[] { new Tool(new CodeExecution()) }
);

var 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.";
var chat = model.StartChat();
var response = await chat.SendMessageAsync(prompt);

foreach (var part in response.Candidates.First().Content.Parts) {
  if (part is ModelContent.TextPart tp) {
    UnityEngine.Debug.Log($"Text = {tp.Text}");
  } else if (part is ModelContent.ExecutableCodePart esp) {
    UnityEngine.Debug.Log($"Code = {esp.Code}, Language = {esp.Language}");
  } else if (part is ModelContent.CodeExecutionResultPart cerp) {
    UnityEngine.Debug.Log($"Outcome = {cerp.Outcome}, Output = {cerp.Output}");
  }
}

تعرَّف على كيفية اختيار نموذج مناسبَين لحالة الاستخدام والتطبيق.

الأسعار

لا يتم فرض أي رسوم إضافية مقابل تفعيل ميزة تنفيذ الرموز البرمجية وتوفيرها كأداة للنموذج. إذا قرّر النموذج استخدام ميزة تنفيذ الرموز البرمجية، فسيتم تحصيل الرسوم منك وفقًا للسعر الحالي لرموز الإدخال والإخراج استنادًا إلى نموذج Gemini الذي تستخدمه.

يوضّح المخطّط البياني التالي نموذج الفوترة لتنفيذ الرموز البرمجية:

مخطّط بياني يوضّح كيفية فوترة الرموز المميّزة عندما يستخدم النموذج ميزة تنفيذ الرموز البرمجية 

في ما يلي ملخّص لكيفية فوترة الرموز المميّزة عندما يستخدم النموذج ميزة تنفيذ الرموز البرمجية:

  • يتم تحصيل رسوم الطلب الأصلي مرة واحدة. يتم تصنيف الرموز المميّزة على أنّها وسيطة، وتتم فوترتها على أنّها رموز مميّزة للإدخال.

  • يتم احتساب تكلفة الرمز الذي تم إنشاؤه ونتيجة الرمز الذي تم تنفيذه على النحو التالي:

    • عند استخدامها أثناء تنفيذ الرموز البرمجية، يتم تصنيفها على أنّها رموز مميّزة وسيطة، ويتم تحصيل رسومها على أنّها رموز مميّزة للإدخال.

    • وعندما يتم تضمينها كجزء من الردّ النهائي، يتم تحصيل رسومها على أنّها رموز مميّزة ناتجة.

  • يتم احتساب تكلفة الملخّص النهائي في الردّ النهائي على أنّه رموز مخرجات.

يتضمّن Gemini API عدد الرموز المميّزة الوسيطة في الردّ من واجهة برمجة التطبيقات، لكي تعرف سبب تحصيل رسوم منك مقابل رموز الإدخال المميّزة التي تتجاوز طلبك الأولي.

يُرجى العِلم أنّ الرمز البرمجي الذي يتم إنشاؤه يمكن أن يتضمّن نصوصًا ومخرجات متعدّدة الوسائط، مثل الصور.

القيود وأفضل الممارسات

  • يمكن للنموذج إنشاء رموز Python وتنفيذها فقط. ولا يمكنه عرض عناصر أخرى، مثل ملفات الوسائط.

  • يمكن أن يستمر تنفيذ الرمز البرمجي لمدة 30 ثانية كحد أقصى قبل انتهاء المهلة.

  • في بعض الحالات، قد يؤدي تفعيل ميزة تنفيذ الرموز البرمجية إلى تراجع في جوانب أخرى من مخرجات النموذج (مثل كتابة قصة).

  • لا تتيح أداة تنفيذ الرموز البرمجية استخدام معرّفات الموارد المنتظمة (URI) للملفات كإدخال/إخراج. ومع ذلك، تتيح أداة تنفيذ الرموز البرمجية إدخال الملفات وإخراج الرسوم البيانية كوحدات بايت مضمّنة. من خلال استخدام إمكانات الإدخال والإخراج هذه، يمكنك تحميل ملفات CSV وملفات نصية وطرح أسئلة حول الملفات وإنشاء رسومات Matplotlib كجزء من نتيجة تنفيذ الرمز البرمجي. أنواع MIME المتوافقة مع وحدات البايت المضمّنة هي .cpp و.csv و.java و.jpeg و.js و.png و.py و.ts و.xml.

المكتبات المتوافقة

تتضمّن بيئة تنفيذ الرموز البرمجية المكتبات التالية. لا يمكنك تثبيت مكتباتك الخاصة.


تقديم ملاحظات حول تجربتك مع "Firebase AI Logic"