הרצת קוד

תכונת הרצת הקוד של Gemini API מאפשרת למודל ליצור ולהריץ קוד Python, וללמוד באופן איטרטיבי מהתוצאות עד שהוא מגיע לפלט הסופי. אתם יכולים להשתמש ביכולת הזו של הרצת קוד כדי ליצור אפליקציות שמפיקות תועלת מהסקת מסקנות שמבוססת על קוד ומפיקות פלט טקסט. לדוגמה, אפשר להשתמש בהרצת קוד באפליקציה שפותרת משוואות או מעבדת טקסט.

‫Gemini API מספק הרצת קוד ככלי, בדומה לקריאה להפעלת פונקציות. אחרי שמוסיפים את הרצת הקוד ככלי, המודל מחליט מתי להשתמש בו.

סביבת הרצת הקוד כוללת את הספריות הבאות. אי אפשר להתקין ספריות משלכם.

מודלים נתמכים

המודלים הבאים תומכים בהרצת קוד:

לחצו כדי להרחיב את רשימת המודלים הנתמכים

איך מתחילים להשתמש בהרצת קוד

ההנחה היא שכבר השלמתם את שלבי ההגדרה וההתקנה שמפורטים במאמר תחילת העבודה עם Gemini Enterprise Agent Platform.

הפעלת הרצת קוד

כדי לאפשר למודל להשתמש בהרצת קוד, מוסיפים אותו לרשימה tools כשמגדירים את המודל:

Python

התקנה

pip install --upgrade google-genai

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    HttpOptions,
    Tool,
    ToolCodeExecution,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))
model_id = "gemini-3.5-flash"

code_execution_tool = Tool(code_execution=ToolCodeExecution())
response = client.models.generate_content(
    model=model_id,
    contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
    config=GenerateContentConfig(
        tools=[code_execution_tool],
        temperature=0,
    ),
)
print("# Code:")
print(response.executable_code)
print("# Outcome:")
print(response.code_execution_result)

# Example response:
# # Code:
# def fibonacci(n):
#     if n <= 0:
#         return 0
#     elif n == 1:
#         return 1
#     else:
#         a, b = 0, 1
#         for _ in range(2, n + 1):
#             a, b = b, a + b
#         return b
#
# fib_20 = fibonacci(20)
# print(f'{fib_20=}')
#
# # Outcome:
# fib_20=6765

Go

thought איך מתקינים או מעדכנים את Go

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithCodeExec shows how to generate text using the code execution tool.
func generateWithCodeExec(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	prompt := "Calculate 20th fibonacci number. Then find the nearest palindrome to it."
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: prompt},
		},
			Role: genai.RoleUser},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{CodeExecution: &genai.ToolCodeExecution{}},
		},
		Temperature: genai.Ptr(float32(0.0)),
	}
	modelName := "gemini-2.5-flash"

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	for _, p := range resp.Candidates[0].Content.Parts {
		if p.Text != "" {
			fmt.Fprintf(w, "Gemini: %s", p.Text)
		}
		if p.ExecutableCode != nil {
			fmt.Fprintf(w, "Language: %s\n%s\n", p.ExecutableCode.Language, p.ExecutableCode.Code)
		}
		if p.CodeExecutionResult != nil {
			fmt.Fprintf(w, "Outcome: %s\n%s\n", p.CodeExecutionResult.Outcome, p.CodeExecutionResult.Output)
		}
	}

	// Example response:
	// Gemini: Okay, I can do that. First, I'll calculate the 20th Fibonacci number. Then, I need ...
	//
	// Language: PYTHON
	//
	// def fibonacci(n):
	//    ...
	//
	// fib_20 = fibonacci(20)
	// print(f'{fib_20=}')
	//
	// Outcome: OUTCOME_OK
	// fib_20=6765
	//
	// Now that I have the 20th Fibonacci number (6765), I need to find the nearest palindrome. ...
	// ...

	return nil
}

Node.js

התקנה

npm install @google/genai

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateAndExecuteCode(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents:
      'Calculate 20th fibonacci number. Then find the nearest palindrome to it.',
    config: {
      tools: [{codeExecution: {}}],
      temperature: 0,
    },
  });

  console.debug(response.executableCode);

  // Example response:
  // Code:
  // function fibonacci(n) {
  //   if (n <= 0) {
  //     return 0;
  //   } else if (n === 1) {
  //     return 1;
  //   } else {
  //     let a = 0, b = 1;
  //     for (let i = 2; i <= n; i++) {
  //       [a, b] = [b, a + b];
  //     }
  //     return b;
  //   }
  // }
  //
  // const fib20 = fibonacci(20);
  // console.log(`fib20=${fib20}`);

  console.debug(response.codeExecutionResult);

  // Outcome:
  // fib20=6765

  return response.codeExecutionResult;
}

Java

thought איך מתקינים או מעדכנים את Java

מידע נוסף זמין ב מאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Tool;
import com.google.genai.types.ToolCodeExecution;

public class ToolsCodeExecWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text using the Code Execution tool
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Create a GenerateContentConfig and set codeExecution tool
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build())
              .temperature(0.0F)
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
              contentConfig);

      System.out.println("Code: \n" + response.executableCode());
      System.out.println("Outcome: \n" + response.codeExecutionResult());
      // Example response
      // Code:
      // def fibonacci(n):
      //    if n <= 0:
      //        return 0
      //    elif n == 1:
      //        return 1
      //    else:
      //        a, b = 1, 1
      //        for _ in range(2, n):
      //            a, b = b, a + b
      //        return b
      //
      // fib_20 = fibonacci(20)
      // print(f'{fib_20=}')
      //
      // Outcome:
      // fib_20=6765
      return response.executableCode();
    }
  }
}

REST

GenerateContent API

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫GENERATE_RESPONSE_METHOD: סוג התשובה שרוצים שהמודל ייצור. בוחרים שיטה שקובעת איך התשובה של המודל תוחזר:
    • ‫streamGenerateContent: התשובה מועברת בסטרימינג בזמן שהיא נוצרת, כדי שהמשתמשים לא ירגישו את זמן האחזור.
    • ‫generateContent: התשובה מוחזרת אחרי שהיא נוצרת במלואה.
  • ‫LOCATION: האזור שבו הבקשה תעובד.
  • ‫PROJECT_ID: מזהה הפרויקט.
  • ‫MODEL_ID: מזהה המודל שבו רוצים להשתמש.
  • ‫ROLE: התפקיד בשיחה שמשויך לתוכן. חובה לציין תפקיד גם בתרחישי שימוש בפרומפט אחד. הערכים הקבילים כוללים:
    • USER: מציין תוכן שאתם שלחתם.
    • ‫MODEL: מציין את התשובה של המודל.
  • TEXTההוראות בטקסט שצריך לכלול בהנחיה.

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

cat > request.json << 'EOF'
{
  "tools": [{'codeExecution': {}}],
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
}
EOF

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

@'
{
  "tools": [{'codeExecution': {}}],
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
}
'@  | Out-File -FilePath request.json -Encoding utf8

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

Interactions API

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט.
  • ‫MODEL_ID: מזהה המודל שבו רוצים להשתמש.
  • TEXTההוראות בטקסט שצריך לכלול בהנחיה.

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

cat > request.json << 'EOF'
{
  "model": "MODEL_ID",
  "tools": [
    {
      "type": "code_execution"
    }
  ],
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "TEXT"
        }
      ]
    }
  ]
}
EOF

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

@'
{
  "model": "MODEL_ID",
  "tools": [
    {
      "type": "code_execution"
    }
  ],
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "TEXT"
        }
      ]
    }
  ]
}
'@  | Out-File -FilePath request.json -Encoding utf8

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

איך משתמשים בהרצת קוד בשיחה

אתם יכולים להשתמש בהרצת קוד גם כחלק משיחה.

REST

GenerateContent API

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

cat > request.json << 'EOF'
{
  "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."
      }
    }
  ]
}
EOF

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.5-flash:generateContent"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

@'
{
  "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."
      }
    }
  ]
}
'@  | Out-File -FilePath request.json -Encoding utf8

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.5-flash:generateContent" | Select-Object -Expand Content

Interactions API

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

cat > request.json << 'EOF'
{
  "model": "gemini-3.8-flash",
  "tools": [
    {
      "type": "code_execution"
    }
  ],
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "Can you print \"Hello world!\"?"
        }
      ]
    },
    {
      "type": "code_execution_call",
      "id": "code_call_71021",
      "arguments": {
        "language": "PYTHON",
        "code": "\nprint(\"hello world!\")\n"
      }
    },
    {
      "type": "code_execution_result",
      "call_id": "code_call_71021",
      "result": "hello world!\n"
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "I have printed \"hello world!\" using the provided python code block. \n"
        }
      ]
    },
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "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."
        }
      ]
    }
  ]
}
EOF

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

@'
{
  "model": "gemini-3.8-flash",
  "tools": [
    {
      "type": "code_execution"
    }
  ],
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "Can you print \"Hello world!\"?"
        }
      ]
    },
    {
      "type": "code_execution_call",
      "id": "code_call_71021",
      "arguments": {
        "language": "PYTHON",
        "code": "\nprint(\"hello world!\")\n"
      }
    },
    {
      "type": "code_execution_result",
      "call_id": "code_call_71021",
      "result": "hello world!\n"
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "I have printed \"hello world!\" using the provided python code block. \n"
        }
      ]
    },
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "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."
        }
      ]
    }
  ]
}
'@  | Out-File -FilePath request.json -Encoding utf8

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" | Select-Object -Expand Content

(רק ב-Gemini 3 Flash) איך משתמשים בהרצת קוד עם תמונות

‫Gemini 3 Flash יכול לכתוב ולהריץ קוד Python כדי לשנות ולבדוק תמונות באופן פעיל. אתם יכולים להשתמש בהרצת קוד עם תמונות כדי:

  • הגדלה ובדיקה של תמונות: זיהוי מקרים שבהם הפרטים קטנים מדי (למשל, קריאת מד שנמצא רחוק מהמצלמה) וכתיבת קוד לחיתוך ובדיקה מחדש של האזור ברזולוציה גבוהה יותר.

  • מתמטיקה חזותית: הפעלת חישובים מרובי שלבים באמצעות קוד (כמו חיבור פריטים בקבלה).

  • הוספת הערות לתמונות: הוספת הערות לתמונות כדי לענות על שאלות, למשל ציור חצים בין אובייקטים כדי להראות קשרים.

כדי להשתמש בהרצת קוד עם תמונות, מפעילים את הרצת הקוד כשמגדירים את המודל ושולחים הנחיה עם תמונה שהמודל יבדוק:

Python

GenerateContent API

# Example input image
image_path = "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/chips.jpeg"
image_bytes = requests.get(image_path).content
image = types.Part.from_bytes(
  data=image_bytes, mime_type="image/jpeg"
)

response = client.models.generate_content(
    model=MODEL_ID,
    contents=[image, "Locate the ESMT chip. What are the numbers on the chip?"],
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution)]
    ),
)

Interactions API

import base64
from google import genai
import requests

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# Example input image
image_path = "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/chips.jpeg"
image_bytes = requests.get(image_path).content
base64_image = base64.b64encode(image_bytes).decode("utf-8")

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "image",
            "data": base64_image,
            "mime_type": "image/jpeg",
        },
        {
            "type": "text",
            "text": "Locate the ESMT chip. What are the numbers on the chip?",
        },
    ],
    tools=[{"type": "code_execution"}],
)

for step in interaction.steps:
    if step.type == "code_execution_call":
        print(f"Code:\n{step.arguments.code}")
    elif step.type == "code_execution_result":
        print(f"Output:\n{step.result}")
    elif step.type == "model_output":
        print(step.content[0].text)

הרצת קוד לעומת קריאה להפעלת פונקציות

הרצת קוד וקריאה להפעלת פונקציות הן תכונות דומות:

  • הרצת קוד מאפשרת למודל להריץ קוד בקצה העורפי של ה-API בסביבה קבועה ומבודדת.
  • התכונה "קריאה להפעלת פונקציות" מאפשרת להריץ את הפונקציות שהמודל מבקש, בכל סביבה שרוצים.

באופן כללי, עדיף להשתמש בהרצת קוד אם היא מתאימה לתרחיש לדוגמה שלכם. הרצת קוד היא תכונה פשוטה יותר לשימוש (רק צריך להפעיל אותה) והיא פותרת את הבעיה בבקשה אחת של GenerateContent. קריאה להפעלת פונקציות דורשת בקשת GenerateContent נוספת כדי לשלוח בחזרה את הפלט מכל בקשה להפעלת פונקציה.

ברוב המקרים, כדאי להשתמש בקריאה להפעלת פונקציות אם יש לכם פונקציות משלכם שאתם רוצים להריץ באופן מקומי, וכדאי להשתמש בהרצת קוד אם אתם רוצים שה-API יכתוב ויריץ קוד Python בשבילכם ויחזיר את התוצאה.

חיוב

הפעלת הרצת הקוד מ-Gemini API לא כרוכה בתשלום נוסף. החיוב יתבצע לפי התעריף הנוכחי של טוקנים לקלט ולפלט, בהתאם למודל Gemini שבו אתם משתמשים.

הנה עוד כמה דברים שכדאי לדעת על החיוב על הרצת קוד:

  • אתם מחויבים רק פעם אחת על הטוקנים של הקלט שאתם מעבירים למודל ועל הטוקנים של הקלט שנוצרים על ידי כלי הרצת הקוד.
  • החיוב הוא על הטוקנים הסופיים של הפלט שמוחזרים בתגובה מה-API.

תרשים של תהליך החיוב על השימוש בכלי להרצת קוד, כמו שמתואר בטקסט שבהמשך.

  • החיוב מתבצע לפי התעריף הנוכחי של טוקנים של קלט ופלט, בהתאם למודל Gemini שבו אתם משתמשים.
  • אם Gemini משתמש בהרצת קוד כשהוא יוצר את התשובה, ההנחיה המקורית, הקוד שנוצר והתוצאה של הרצת הקוד מסומנים כטוקנים של ביניים ומחויבים כטוקנים של קלט.
  • ‫Gemini יוצר סיכום ומחזיר את הקוד שנוצר, את התוצאה של הקוד שהופעל ואת הסיכום הסופי. הם מחויבים כטוקנים של פלט.
  • ‫Gemini API כולל ספירת טוקנים של ביניים בתגובה מה-API, כדי שתוכלו לעקוב אחרי טוקנים נוספים של קלט מעבר לאלה שהועברו בהנחיה הראשונית.

הקוד שנוצר יכול לכלול גם טקסט וגם פלט מולטימודלי, כמו תמונות.

מגבלות

  • המודל יכול רק ליצור ולהריץ קוד. הוא לא יכול להחזיר פריטים אחרים כמו קובצי מדיה.
  • כלי הרצת הקוד לא תומך בכתובות URI של קבצים כקלט או כפלט. עם זאת, כלי הרצת הקוד תומך בקלט של קבצים ובפלט של תרשימים כבייטים מוטבעים. בעזרת יכולות הקלט והפלט האלה, אתם יכולים להעלות קובצי CSV וטקסט, לשאול שאלות לגבי הקבצים וליצור תרשימי Matplotlib כחלק מתוצאת הרצת הקוד. סוגי ה-MIME הנתמכים לבייטים מוטבעים הם .cpp,‏ .csv,‏ .java,‏ .jpeg,‏ .js,‏ .png,‏ .py,‏ .ts ו-.xml.
  • הרצת הקוד יכולה להימשך עד 30 שניות לפני שהזמן הקצוב לתפוגה נגמר.
  • במקרים מסוימים, הפעלת הרצת הקוד עלולה להוביל לרגרסיות בתחומים אחרים של הפלט מהמודל (לדוגמה, כתיבת סיפור).

שיטות מומלצות ואזהרות

כשמשתמשים בהרצת קוד, חשוב לפעול לפי השיטות המומלצות וההנחיות הבאות:

  • הוראות ביצוע מפורשות: מודלים גדולים של שפה (LLM) עשויים להשתמש כברירת מחדל בהסקת מסקנות לשונית, אלא אם תורו להם אחרת. כשאתם מספקים הוראות להרצת קוד, השתמשו בהנחיות מפורשות (לדוגמה, "תמיד צריך להריץ את הסקריפט" או "אל תחשב ישירות").
  • בידוד רשת: לארגז החול להרצת הקוד אין גישה לאינטרנט הציבורי. סקריפטים לא יכולים לשלוח בקשות HTTP חיצוניות או להוריד משאבים חיצוניים.
  • ביצוע ללא שמירת מצב: כל ביצוע פועל בקונטיינר זמני. קבצים שנוצרו או שונו במהלך סבב אחד לא נשמרים בסבבים או בסשנים הבאים.
  • יחסי תלות: רק ספריות Python רגילות וחבילות מניפולציה של נתונים שמותקנות מראש (כמו numpy או pandas) זמינות. הסביבה לא תומכת בהתקנות דינמיות של חבילות זמן ריצה (כמו pip install).
  • קלט/פלט סטנדרטי: כותבים סקריפטים שמקבלים קלט מארגומנטים של שורת הפקודה (sys.argv) או מקלט סטנדרטי (sys.stdin), ומדפיסים את התוצאה ישירות לפלט סטנדרטי (sys.stdout).