程式碼執行

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

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

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

支援的模型

以下模型支援程式碼執行作業:

開始執行程式碼

本節假設您已完成 Gemini API 快速入門中的設定步驟。

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

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

Gen AI SDK for 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

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for 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},
		}},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{CodeExecution: &genai.ToolCodeExecution{}},
		},
		Temperature: genai.Ptr(0.0),
	}
	modelName := "gemini-2.0-flash-001"

	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
}

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 會產生摘要,並傳回產生的程式碼、執行的程式碼結果和最終摘要。這些項目會以輸出符記計費。
  • Gemini API 會在 API 回應中加入中繼符號計數,方便您追蹤初始提示中傳遞的其他輸入符號。

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

限制

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