توفّر Gemini API أداة تنفيذ رموز برمجية تتيح للنموذج إنشاء رموز Python وتنفيذها. يمكن للنموذج بعد ذلك التعلّم بشكل متكرّر من نتائج تنفيذ الرمز البرمجي إلى أن يصل إلى نتيجة نهائية. يمكنك استخدام تنفيذ الرمز البرمجي لإنشاء تطبيقات تستفيد من الاستدلال المستنِد إلى الرموز البرمجية. على سبيل المثال، يمكنك استخدام تنفيذ الرموز لحلّ المعادلات أو معالجة النصوص. يمكنك أيضًا استخدام المكتبات المضمّنة في بيئة تنفيذ الرمز البرمجي لإنجاز مهام أكثر تخصصًا.
لا يمكن لخدمة Gemini تنفيذ الرموز البرمجية إلا بلغة Python. سيظل بإمكانك أن تطلب من Gemini توليد رمز بلغة أخرى، ولكن لا يمكن للنموذج استخدام أداة تنفيذ الرمز لتشغيله.
تفعيل تنفيذ الرمز البرمجي
لتفعيل تنفيذ الرمز البرمجي، عليك ضبط أداة تنفيذ الرمز البرمجي في النموذج. ويسمح ذلك للنموذج بإنشاء رمز وتنفيذه.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="What is the sum of the first 50 prime numbers? "
"Generate and run code for the calculation, and make sure you get all 50.",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
let response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: [
"What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.",
],
config: {
tools: [{ codeExecution: {} }],
},
});
const parts = response?.candidates?.[0]?.content?.parts || [];
parts.forEach((part) => {
if (part.text) {
console.log(part.text);
}
if (part.executableCode && part.executableCode.code) {
console.log(part.executableCode.code);
}
if (part.codeExecutionResult && part.codeExecutionResult.output) {
console.log(part.codeExecutionResult.output);
}
});
انتقال
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GOOGLE_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{CodeExecution: &genai.ToolCodeExecution{}},
},
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.0-flash",
genai.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."),
config,
)
fmt.Println(result.Text())
fmt.Println(result.ExecutableCode())
fmt.Println(result.CodeExecutionResult())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-d ' {"tools": [{"code_execution": {}}],
"contents": {
"parts":
{
"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."
}
},
}'
قد يبدو الناتج على النحو التالي، وقد تم تنسيقه لسهوله القراءة:
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
: نتيجة الرمز القابل للتنفيذ
تختلف اصطلاحات التسمية لهذه الأجزاء حسب لغة البرمجة.
استخدام ميزة "تنفيذ الرموز" في المحادثة
يمكنك أيضًا استخدام تنفيذ الرموز البرمجية كجزء من محادثة.
Python
from google import genai
from google.genai import types
client = genai.Client()
chat = client.chats.create(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
response = chat.send_message("I have a math question for you.")
print(response.text)
response = chat.send_message(
"What is the sum of the first 50 prime numbers? "
"Generate and run code for the calculation, and make sure you get all 50."
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
JavaScript
import {GoogleGenAI} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const chat = ai.chats.create({
model: "gemini-2.0-flash",
history: [
{
role: "user",
parts: [{ text: "I have a math question for you:" }],
},
{
role: "model",
parts: [{ text: "Great! I'm ready for your math question. Please ask away." }],
},
],
config: {
tools: [{codeExecution:{}}],
}
});
const response = await chat.sendMessage({
message: "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
});
console.log("Chat response:", response.text);
انتقال
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GOOGLE_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{CodeExecution: &genai.ToolCodeExecution{}},
},
}
chat, _ := client.Chats.Create(
ctx,
"gemini-2.0-flash",
config,
nil,
)
result, _ := chat.SendMessage(
ctx,
genai.Part{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.",
},
)
fmt.Println(result.Text())
fmt.Println(result.ExecutableCode())
fmt.Println(result.CodeExecutionResult())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"tools": [{"code_execution": {}}],
"contents": [
{
"role": "user",
"parts": [{
"text": "Can you print \"Hello world!\"?"
}]
},{
"role": "model",
"parts": [
{
"text": ""
},
{
"executable_code": {
"language": "PYTHON",
"code": "\nprint(\"hello world!\")\n"
}
},
{
"code_execution_result": {
"outcome": "OUTCOME_OK",
"output": "hello world!\n"
}
},
{
"text": "I have printed \"hello world!\" using the provided python code block. \n"
}
],
},{
"role": "user",
"parts": [{
"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."
}]
}
]
}'
الإدخال/الإخراج
بدءًا من Gemini 2.0 Flash، يتيح تنفيذ الرمز البرمجي إدخال الملفات وعرض الرسوم البيانية. باستخدام إمكانات الإدخال والإخراج هذه، يمكنك تحميل ملفات CSV وملفات نصية وطرح أسئلة حول الملفات وإنشاء الرسوم البيانية Matplotlib كجزءٍ من الردّ. يتم عرض ملفات الإخراج كصور مضمّنة في الاستجابة.
أسعار وحدات الإدخال والإخراج
عند استخدام عمليات الإدخال/الإخراج لتنفيذ الرموز، يتم تحصيل رسوم منك مقابل الرموز المميّزة للدخل والرموز المميّزة للمخرج:
إدخال الرموز المميزة:
- طلب المستخدم
رموز الإخراج:
- الرمز الذي أنشأه النموذج
- ناتج تنفيذ الرمز البرمجي في بيئة الرموز البرمجية
- الملخّص الذي أنشأه النموذج
تفاصيل الإدخال/الإخراج
عند العمل مع وحدات الإدخال والإخراج الخاصة بتنفيذ الرموز البرمجية، يُرجى الانتباه إلى التفاصيل الفنية التالية:
- يبلغ الحد الأقصى لوقت تشغيل بيئة الرموز البرمجية 30 ثانية.
- إذا تسبّبت بيئة الرموز البرمجية في حدوث خطأ، قد يقرّر النموذج مجددًا إنشاء مخرجات الرموز البرمجية. ويمكن أن يحدث ذلك حتى 5 مرات.
- يتم تحديد الحد الأقصى لحجم إدخال الملف من خلال نافذة رمز نموذج المحاكاة. في AI Studio، باستخدام Gemini Flash 2.0، يبلغ الحد الأقصى لحجم ملف الإدخال مليون رمز مميّز (حوالي 2 ميغابايت لملفات النصوص من أنواع الإدخال المتوافقة). إذا حمّلت ملفًا كبيرًا جدًا، لن يسمح لك "استوديو الذكاء الاصطناعي" بإرساله.
- يعمل تنفيذ الرموز البرمجية بشكل أفضل مع ملفات النصوص وملفات CSV.
- يمكن تمرير ملف الإدخال بتنسيق
part.inlineData
أوpart.fileData
(يتم تحميله من خلال Files API)، ويتم دائمًا عرض ملف الإخراج بتنسيقpart.inlineData
.
منعطف واحد | ثنائية الاتجاه (Multimodal Live API) | |
---|---|---|
الطُرز المتوافقة | جميع نماذج Gemini 2.0 | النماذج التجريبية لإعلانات فلاش فقط |
أنواع إدخال الملفات المتوافقة | .png و.jpeg و.csv و.xml و.cpp و.java و.py و.js و.ts | .png و.jpeg و.csv و.xml و.cpp و.java و.py و.js و.ts |
مكتبات الرسم البياني المتوافقة | Matplotlib | Matplotlib |
استخدام أدوات متعددة | لا | نعم |
الفوترة
لا يتم تحصيل أي رسوم إضافية مقابل تفعيل تنفيذ الرموز البرمجية من Gemini API. سيتم تحصيل الرسوم منك وفقًا للسعر الحالي لوحدات ترميز الإدخال والإخراج استنادًا إلى نموذج Gemini الذي تستخدمه.
في ما يلي بعض المعلومات الأخرى التي يجب معرفتها عن الفوترة مقابل تنفيذ الرموز:
- يتم تحصيل رسوم منك مرة واحدة فقط مقابل الرموز المميّزة للدخل التي ترسلها إلى النموذج، ويتم تحصيل رسوم منك مقابل الرموز المميّزة النهائية للمخرجات التي يعرضها لك النموذج.
- يتم احتساب الرموز المميّزة التي تمثّل الرمز البرمجي ال��ي تم إن��ا��ه ��لى أنّها رموز إخراج. يمكن أن يتضمّن الرمز المبرمَج الذي تم إنشاؤه نصًا ونتائج متعددة الوسائط، مثل الصور.
- تُحتسَب نتائج تنفيذ الرموز البرمجية أيضًا كرموز إخراج.
يظهر نموذج الفوترة في الرسم البياني التالي:
- يتم تحصيل الرسوم منك وفقًا للسعر الحالي لوحدات ترميز الإدخال والإخراج استنادًا إلى نموذج Gemini الذي تستخدمه.
- إذا كان Gemini يستخدم تنفيذ الرمز البرمجي عند إنشاء الردّ، يتم تصنيف العبارة الأصلية والرمز البرمجي الذي تم إنشاؤه ونتيجة الرمز البرمجي الذي تم تنفيذه على أنّه رموز وسيطة ويتم تصنيفها على أنّها رموز إدخال.
- بعد ذلك، تنشئ أداة Gemini ملخّصًا وتُرجع الرمز الذي تم إنشاؤه ونتيجة الرمز الذي تم تنفيذه والملخّص النهائي. ويتم تحصيل رسومها على أنّها رموز إخراج.
- تتضمّن Gemini API عددًا وسيطًا من الرموز المميّزة في ردّ واجهة برمجة التطبيقات، كي تتمكّن من معرفة سبب تلقّي رموز مميّزة إضافية للدخل غير تلك المضمّنة في الطلب الأولي.
القيود
- لا يمكن للنموذج إنشاء رمز وتنفيذه إلا. ولا يمكنه عرض عناصر أخرى، مثل ملفات الوسائط.
- في بعض الحالات، يمكن أن يؤدي تفعيل تنفيذ الرمز إلى حدوث تراجع في مجالات أخرى من نتائج النموذج (مثل كتابة قصة).
- هناك بعض الاختلافات في قدرة النماذج المختلفة على استخدام تنفيذ الرمز المبرمَج بنجاح.
المكتبات المتوافقة
تتضمّن بيئة تنفيذ الرموز البرمجية المكتبات التالية:
- attrs
- شطرنج
- contourpy
- fpdf
- geopandas
- imageio
- jinja2
- joblib
- jsonschema
- jsonschema-specifications
- lxml
- matplotlib
- mpmath
- مكتبة نامبي
- opencv-python
- openpyxl
- حزمة محتوى التطبيق
- باندا
- وسادة
- protobuf
- pylatex
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- reportlab
- مكتبة ساي كيت ليرن
- scipy
- seaborn
- ستة
- striprtf
- sympy
- جدولة
- tensorflow
- toolz
- xlrd
لا يمكنك تثبيت مكتباتك الخاصة.
الخطوات التالية
- جرِّب استخدام تنفيذ الرمز في Colab.
- تعرَّف على أدوات Gemini API الأخرى: