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


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

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

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

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

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

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

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

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

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

  • 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) وتهيئة خدمة الخلفية لمقدّم خدمة 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 الذي تستخدمه.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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