程式碼執行

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

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

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

支援的模型

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

開始執行程式碼

本節假設您已完成 Gemini API 快速入門導覽課程中顯示的設定和配置步驟。

啟用模型上的程式碼執行功能

您可以啟用基本程式碼執行功能,如下所示:

Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,透過 Vertex AI 使用 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_VERTEXAI=True

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

client = genai.Client(http_options=HttpOptions(api_version="v1"))
model_id = "gemini-2.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 使用 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_VERTEXAI=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: "user"},
	}
	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 使用 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_VERTEXAI=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 generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const ai = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await ai.models.generateContent({
    model: 'gemini-2.5-flash-preview-05-20',
    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: {}}],
      temperature: 0,
    },
  });

  console.debug(response.executableCode);
  console.debug(response.codeExecutionResult);

  return response.codeExecutionResult;
}

REST

使用任何要求資料之前,請先替換以下項目:

  • GENERATE_RESPONSE_METHOD:您希望模型生成的回應類型。 選擇生成模型回覆傳回方式的方法:
    • streamGenerateContent:在生成回覆時串流傳輸,減少人類觀眾的延遲感。
    • generateContent:系統會在完整生成回覆後傳回。
  • LOCATION:處理要求的區域。可用的選項包括:

    按一下即可展開可用地區的部分清單

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • 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-2.0-flash-001: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."
        }
      }
    ]
  }'

程式碼執行與函式呼叫

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

  • 模型可透過程式碼執行功能,在 API 後端的固定隔離環境中執行程式碼。
  • 函式呼叫功能可讓您在任何環境中,執行模型要求執行的函式。

一般來說,如果程式碼執行功能可以處理您的用途,建議優先使用。程式碼執行功能使用起來更簡單 (只要啟用即可),而且會在單一 GenerateContent 要求中解決問題。函式呼叫會額外發出 GenerateContent 要求,將每次函式呼叫的輸出內容傳回。

在大多數情況下,如果您有想在本機執行的函式,應使用函式呼叫;如果您想讓 API 為您撰寫及執行 Python 程式碼並傳回結果,則應使用程式碼執行功能。

帳單

透過 Gemini API 啟用程式碼執行功能無須額外付費。系統會根據您使用的 Gemini 模型,以目前的輸入和輸出權杖費率計費。

以下是程式碼執行計費的其他注意事項:

  • 您只需為傳遞至模型的輸入權杖付費一次,程式碼執行工具產生的中繼輸入權杖則不需付費。
  • 系統會根據 API 回應中傳回的最終輸出權杖向您收費。

下圖說明程式碼執行工具的使用計費流程,詳情請參閱下文。

  • 系統會根據您使用的 Gemini 模型,以目前的輸入和輸出權杖費率計費。
  • 如果 Gemini 在生成回覆時執行程式碼,原始提示、生成的程式碼和執行的程式碼結果會標示為中間權杖,並以輸入權杖計費。
  • 接著生成摘要,並傳回生成的程式碼、執行的程式碼結果和最終摘要。這些代幣會以輸出權杖計費。
  • Gemini API 會在 API 回應中提供中繼權杖計數,因此您可以追蹤初始提示中傳遞的權杖以外的任何額外輸入權杖。

生成的程式碼可能包含文字和多模態輸出內容,例如圖片。

限制

  • 模型只能生成及執行程式碼,無法傳回其他構件,例如媒體檔案。
  • 程式碼執行工具不支援將檔案 URI 做為輸入/輸出內容。不過,程式碼執行工具支援檔案輸入和圖表輸出,以內嵌位元組的形式呈現。透過這些輸入和輸出功能,您可以上傳 CSV 和文字檔、詢問檔案相關問題,以及產生 Matplotlib 圖表做為程式碼執行結果的一部分。內嵌位元組支援的 MIME 類型為 .cpp.csv.java.jpeg.js.png.py.ts.xml
  • 程式碼執行時間最長為 30 秒,超過就會逾時。
  • 在某些情況下,啟用程式碼執行功能可能會導致模型輸出內容的其他部分出現回歸現象 (例如撰寫故事)。