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.5-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({}); let response = await ai.models.generateContent({ model: "gemini-2.5-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, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } result, _ := client.Models.GenerateContent( ctx, "gemini-2.5-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.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_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.5-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({}); const chat = ai.chats.create({ model: "gemini-2.5-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, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } chat, _ := client.Chats.Create( ctx, "gemini-2.5-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.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_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.inlineData
或part.fileData
傳遞 (透過 Files API 上傳),輸出檔案一律以part.inlineData
形式傳回。
單輪 | 雙向 (Multimodal Live API) | |
---|---|---|
支援的機型 | 所有 Gemini 2.0 和 2.5 模型 | 僅限 Flash 實驗模型 |
支援的檔案輸入類型 | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts |
支援的繪圖程式庫 | Matplotlib、seaborn | Matplotlib、seaborn |
使用多種工具 | 是 (僅限程式碼執行 + 建立基準) | 是 |
帳單
啟用 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
您無法安裝自己的程式庫。
後續步驟
- 試用程式碼執行 Colab。
- 瞭解其他 Gemini API 工具: