執行程式碼

有了 Gemini API 的執行程式碼功能,模型可生成以及執行 Python 程式碼,並根據結果反覆試驗學習,直到生成最終輸出內容。透過這項執行程式碼功能,您能建構根據程式碼進行推論、生成文字輸出內容的應用程式。舉例來說,您可以在應用程式中使用執行程式碼功能,解開方程式或處理文字。

Gemini API 提供執行程式碼工具,與函式呼叫類似。將程式碼執行功能新增為工具後,模型會決定何時使用這項工具。

程式碼執行環境包含下列程式庫。您無法安裝自己的程式庫。

支援的模型

下列模型支援執行程式碼:

按一下即可展開支援的模型

開始執行程式碼

本節假設您已完成「開始使用 Gemini Enterprise Agent Platform」中的設定步驟。

啟用執行程式碼功能

設定模型時,只要將執行程式碼功能加入 tools 清單,即可啟用這項功能:

Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考文件。

設定環境變數,以便透過 Vertex AI 使用 Google Gen AI SDK:

# 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

瞭解如何安裝或更新 Go。

詳情請參閱 SDK 參考文件。

設定環境變數,以便透過 Vertex AI 使用 Google Gen AI SDK:

# 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 參考文件。

設定環境變數,以便透過 Vertex AI 使用 Google Gen AI SDK:

# 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

瞭解如何安裝或更新 Java。

詳情請參閱 SDK 參考文件。

設定環境變數,以便透過 Vertex AI 使用 Google Gen AI SDK:

# 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

使用任何要求資料之前,請先修改下列項目的值:

  • GENERATE_RESPONSE_METHOD:您希望模型生成的回覆類型。選擇方法,生成模型回覆:
    • streamGenerateContent:回覆生成時會以串流方式傳送,減少使用者感受到的延遲。
    • generateContent:系統會在完整生成回覆後傳回。
  • LOCATION:處理要求的區域。
  • PROJECT_ID:您的專案 ID。。
  • MODEL_ID:要使用的模型 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 回覆。

在對話中使用執行程式碼功能

您也可以在對話中使用執行程式碼功能。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/test-project/locations/global/publishers/google/models/gemini-3.5-flash:generateContent -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 3 Flash) 執行程式碼時使用圖片

Gemini 3 Flash 可編寫及執行 Python 程式碼,主動操控及檢查圖片。您可以搭配圖片使用執行程式碼功能,

  • 縮放及檢查圖片:偵測細節是否過小 (例如讀取距離相機太遠的儀表),並編寫程式碼,以較高解析度裁剪及重新檢查該區域。

  • 視覺數學:使用程式碼執行多步驟計算 (例如加總收據上的明細項目)。

  • 圖片註解:在圖片中加入註解來回答問題,例如在物件之間繪製箭頭來表示關係。

如要搭配圖片執行程式碼,請在設定模型時啟用執行程式碼功能,並傳送含有圖片的提示,讓模型檢查:

Python

# 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)]
    ),
)
      

執行程式碼與函式呼叫

執行程式碼和呼叫函式是類似的功能:

  • 執行程式碼功能可讓模型在 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 秒,超過即逾時。
  • 在某些情況下,啟用執行程式碼功能可能會導致模型輸出內容的其他部分 (例如撰寫故事) 出現迴歸。

最佳做法和注意事項

使用程式碼執行功能時,請遵循下列最佳做法和指南:

  • 明確的執行指令:除非您另有指示,否則大型語言模型可能會預設為語言推理。提供程式碼執行指令時,請使用明確的指令 (例如「一律執行指令碼」或「請勿直接計算」)。
  • 網路隔離:執行程式碼沙箱無法存取公開網際網路。指令碼無法發出外部 HTTP 要求或下載外部資源。
  • 無狀態執行:每次執行都會在臨時容器中執行。在某個回合建立或修改的檔案,不會保留到後續回合或工作階段。
  • 依附元件:僅支援標準 Python 程式庫和預先安裝的資料操控套件 (例如 numpy 或 pandas)。環境不支援動態執行階段套件安裝 (例如 pip install)。
  • 標準 I/O:編寫指令碼,接受來自指令列引數 (sys.argv) 或標準輸入內容 (sys.stdin) 的輸入內容,並直接將結果輸出至標準輸出內容 (sys.stdout)。