Gemini API 程式碼執行功能可讓模型產生及執行 Python 程式碼,並根據結果進行迭代學習,直到產生最終輸出結果為止。您可以使用這項程式碼執行功能,建構可從程式碼推理中受益,並產生文字輸出的應用程式。舉例來說,您可以在解決方程式或處理文字的應用程式中使用程式碼執行功能。
AI Studio 和 Gemini API 都支援程式碼執行作業。在 AI Studio 中,您可以在右側面板的「工具」下方啟用程式碼執行功能。Gemini API 提供程式碼執行工具,類似於函式呼叫。將程式碼執行作業新增為工具後,模型會決定何時使用該工具。
程式碼執行環境包含下列程式庫:altair
、chess
、cv2
、matplotlib
、mpmath
、numpy
、pandas
、pdfminer
、reportlab
、seaborn
、sklearn
、statsmodels
、striprtf
、sympy
和 tabulate
。您無法安裝自己的程式庫。
開始執行程式碼
您也可以使用程式碼執行筆記本:
本節假設您已完成快速入門中顯示的設定步驟。
啟用模型上的程式碼執行功能
您可以啟用模型的程式碼執行作業,如下所示:
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY ")
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
)]
)
)
在 Notebook 中,您可以使用這個輔助函式,以 Markdown 格式顯示所有內容:
def display_code_execution_result(response):
for part in response.candidates[0].content.parts:
if part.text is not None:
display(Markdown(part.text))
if part.executable_code is not None:
code_html = f'<pre style="background-color: #BBBBEE;">{part.executable_code.code}</pre>' # Change code color
display(HTML(code_html))
if part.code_execution_result is not None:
display(Markdown(part.code_execution_result.output))
if part.inline_data is not None:
display(Image(data=part.inline_data.data, format="png"))
display(Markdown("---"))
display_code_execution_result(response)
輸出內容可能如下所示:
好的,我需要計算前 50 個質數的總和。我將使用 Python 指令碼產生前 50 個質數,然後加總。
```python def is_prime(n): """Checks if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(n): """Calculates the sum of the first n prime numbers.""" primes = [] i = 2 while len(primes) < n: if is_prime(i): primes.append(i) i += 1 return sum(primes) # Calculate the sum of the first 50 prime numbers sum_of_first_50_primes = sum_of_primes(50) print(f"The sum of the first 50 prime numbers is: {sum_of_first_50_primes}") ``` **Output:** ``` The sum of the first 50 prime numbers is: 5117 ```
在 Chat 中使用程式碼執行功能
您也可以在聊天中執行程式碼。
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY ")
chat = client.chats.create(
model='gemini-2.0-flash',
config=types.GenerateContentConfig(
tools=[types.Tool(
code_execution=types.ToolCodeExecution
)]
)
)
response = chat.send_message("Can you run some code to bogo-sort this list of numbers?: [2,34,1,65,4]")
display_code_execution_result(response)
對話可能會繼續如下:
據我瞭解,你想讓我對清單 [2, 34, 1, 65, 4] 進行 Bogo 排序。Bogo 排序是效率極低的排序演算法。這項方法會重複洗牌,直到清單排序為止。由於效能極差,因此不建議用於任何大型清單。
不過,為了示範,我可以執行簡易版本,只執行少數幾次迭代,以便展示這個程序。請問要繼續嗎?
response = chat.send_message("Yes, please create the code.")
display_code_execution_result(response)
好的,我會繼續使用隨機排序函式,並檢查清單是否已排序。我會執行最多 10 次疊代。...
輸入/輸出 (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 就不會讓您傳送。
單輪 | 雙向 (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 回應中加入中繼符號計數,讓您瞭解為何除了初始提示之外,還會收到其他輸入符號。
限制
- 模型只能產生及執行程式碼。但無法傳回其他構件,例如媒體檔案。
- 在某些情況下,啟用程式碼執行功能可能會導致模型輸出內容的其他部分 (例如撰寫故事) 出現回歸現象。
- 不同模型使用程式碼執行功能的能力有所差異。