程式碼執行

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.0-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({ apiKey: "GOOGLE_API_KEY" });

let response = await ai.models.generateContent({
  model: "gemini-2.0-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, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    result, _ := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-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.0-flash:generateContent?key=$GOOGLE_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.0-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({ apiKey: "GOOGLE_API_KEY" });

const chat = ai.chats.create({
  model: "gemini-2.0-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, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    chat, _ := client.Chats.Create(
        ctx,
        "gemini-2.0-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.0-flash:generateContent?key=$GOOGLE_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 圖表做為回應。輸出檔案會以內嵌圖片的形式傳回至回應。

I/O 價格

使用程式碼執行 I/O 時,系統會針對輸入符記和輸出符記向您收費:

輸入符記:

  • 使用者提示

輸出符記:

  • 模型產生的程式碼
  • 程式碼環境中的程式碼執行輸出內容
  • 模型產生的摘要

I/O 詳細資料

使用程式碼執行 I/O 時,請注意下列技術細節:

  • 程式碼環境的執行時間上限為 30 秒。
  • 如果程式碼環境產生錯誤,模型可能會決定重新產生程式碼輸出內容。最多可重複 5 次。
  • 檔案輸入大小上限取決於模型符號視窗。在 AI Studio 中,使用 Gemini Flash 2.0 時,輸入檔案大小上限為 100 萬個符記 (支援的輸入類型文字檔約為 2 MB)。如果上傳的檔案過大,AI Studio 就不會讓您傳送。
  • 程式碼執行功能最適合搭配文字和 CSV 檔案使用。
  • 輸入檔案可透過 part.inlineDatapart.fileData 傳遞 (透過 Files API 上傳),輸出檔案一律會以 part.inlineData 格式傳回。
單輪 雙向 (Multimodal Live API)
支援的型號 所有 Gemini 2.0 型號 僅限 Flash 實驗模型
支援的檔案輸入類型 .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts
支援的繪圖程式庫 Matplotlib Matplotlib
使用多種工具

帳單

啟用 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
  • 包裝
  • pandas
  • pillow
  • protobuf
  • pylatex
  • pyparsing
  • PyPDF2
  • python-dateutil
  • python-docx
  • python-pptx
  • reportlab
  • scikit-learn
  • scipy
  • seaborn
  • striprtf
  • sympy
  • 列表
  • tensorflow
  • toolz
  • xlrd

您無法安裝自己的程式庫。

後續步驟