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.5-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({}); let response = await ai.models.generateContent({ model: "gemini-2.5-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); } });
Go
package main import ( "context" "fmt" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } result, _ := client.Models.GenerateContent( ctx, "gemini-2.5-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.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_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.5-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({}); const chat = ai.chats.create({ model: "gemini-2.5-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);
Go
package main import ( "context" "fmt" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } chat, _ := client.Chats.Create( ctx, "gemini-2.5-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.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_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." }] } ] }'
קלט/פלט (I/O)
החל מ-Gemini 2.0 Flash, הפעלת קוד תומכת בקלט של קבצים ובפלט של גרפים. בעזרת היכולות האלה של קלט ופלט, אתם יכולים להעלות קובצי CSV וקובצי טקסט, לשאול שאלות לגבי הקבצים ולקבל תרשימים של Matplotlib כחלק מהתשובה. קבצי הפלט מוחזרים כתמונות מוטבעות בתשובה.
תמחור של קלט/פלט
כשמשתמשים בקלט/פלט של ביצוע קוד, מחויבים על טוקנים של קלט וטוקנים של פלט:
טוקנים של קלט:
- הנחיית משתמש
אסימוני פלט:
- קוד שנוצר על ידי המודל
- פלט של הרצת קוד בסביבת הקוד
- טוקנים של חשיבה
- סיכום שנוצר על ידי המודל
פרטי קלט/פלט
כשעובדים עם קלט/פלט של ביצוע קוד, חשוב לשים לב לפרטים הטכניים הבאים:
- זמן הריצה המקסימלי של סביבת הקוד הוא 30 שניות.
- אם סביבת הקוד יוצרת שגיאה, יכול להיות שהמודל יחליט ליצור מחדש את פלט הקוד. אפשר לעשות את זה עד 5 פעמים.
- הגודל המקסימלי של קובץ קלט מוגבל על ידי חלון הטוקנים של המודל. ב-AI Studio, באמצעות Gemini Flash 2.0, גודל קובץ הקלט המקסימלי הוא מיליון טוקנים (בערך 2MB לקובצי טקסט מסוגי הקלט הנתמכים). אם תעלו קובץ גדול מדי, לא תוכלו לשלוח אותו ב-AI Studio.
- הפעלת קוד עובדת הכי טוב עם קובצי טקסט ו-CSV.
- אפשר להעביר את קובץ הקלט בפורמט
part.inlineData
אוpart.fileData
(העלאה דרך Files API), וקובץ הפלט תמיד מוחזר בפורמטpart.inlineData
.
פנייה אחת | דו-כיווני (ממשק API רב-אופני בזמן אמת) | |
---|---|---|
מודלים נתמכים | כל המודלים של Gemini 2.0 ו-2.5 | רק מודלים ניסיוניים של Flash |
סוגי קבצים נתמכים לקלט | .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts | .png, .jpeg, .csv, .xml, .cpp, .java, .py, .js, .ts |
ספריות שנתמכות לשרטוט | Matplotlib, seaborn | Matplotlib, seaborn |
שימוש במולטיטול | כן (רק ביצוע קוד + ביסוס) | כן |
חיוב
אין עלות נוספת על הפעלת ביצוע קוד מ-Gemini API. תחויבו לפי התעריף הנוכחי של טוקנים של קלט ופלט, בהתאם למודל Gemini שבו אתם משתמשים.
ריכזנו כאן כמה דברים נוספים שכדאי לדעת על חיוב על הפעלת קוד:
- אתם מחויבים רק פעם אחת על טוקני הקלט שאתם מעבירים למודל, ועל טוקני הפלט הסופי שהמודל מחזיר לכם.
- טוקנים שמייצגים קוד שנוצר נספרים כטוקנים של פלט. הקוד שנוצר יכול לכלול טקסט ופלט מולטימודאלי כמו תמונות.
- תוצאות של הרצת קוד נספרות גם הן כאסימוני פלט.
מודל החיוב מוצג בתרשים הבא:
- החיוב מתבצע לפי התעריף הנוכחי של טוקנים של קלט ופלט, בהתאם למודל Gemini שבו אתם משתמשים.
- אם Gemini משתמש בהרצת קוד כדי ליצור את התשובה, ההנחיה המקורית, הקוד שנוצר והתוצאה של הקוד שהורץ מסומנים כטוקנים ביניים והחיוב עליהם הוא כטוקנים של קלט.
- Gemini יוצר סיכום ומחזיר את הקוד שנוצר, את התוצאה של הקוד שהופעל ואת הסיכום הסופי. החיוב הוא על אסימוני פלט.
- Gemini API כולל ספירת אסימונים ביניים בתגובת ה-API, כך שתוכלו לדעת למה אתם מקבלים אסימוני קלט נוספים מעבר להנחיה הראשונית שלכם.
מגבלות
- המודל יכול רק ליצור ולהריץ קוד. הוא לא יכול להחזיר פריטים אחרים, כמו קובצי מדיה.
- במקרים מסוימים, הפעלת ביצוע הקוד עלולה לגרום לרגרסיות בתחומים אחרים של פלט המודל (לדוגמה, כתיבת סיפור).
- יש הבדלים בין המודלים השונים ביכולת שלהם להשתמש בהרצת קוד בהצלחה.
ספריות נתמכות
סביבת ההפעלה של הקוד כוללת את הספריות הבאות:
- attrs
- שחמט
- contourpy
- fpdf
- geopandas
- imageio
- jinja2
- joblib
- jsonschema
- jsonschema-specifications
- lxml
- matplotlib
- mpmath
- numpy
- opencv-python
- openpyxl
- מארז
- פנדות
- כרית
- protobuf
- pylatex
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- reportlab
- scikit-learn
- scipy
- seaborn
- שש
- striprtf
- sympy
- לרכז בטבלה
- tensorflow
- toolz
- xlrd
אי אפשר להתקין ספריות משלכם.
המאמרים הבאים
- אפשר לנסות את המחברת של Colab להרצת קוד.
- מידע על כלים אחרים של Gemini API: