Gemini API 程式碼執行功能可讓模型生成及執行 Python 程式碼,並從結果反覆學習,直到抵達 最終輸出內容您可以使用這項程式碼執行功能建構應用程式 但這些優點可說是靠程式碼推理 並產出文字適用對象 舉例來說,您可以在應用程式中執行程式碼,以解決方程式或 則會處理文字
AI Studio 和 Gemini API 都能執行程式碼。在 AI Studio 中 你可以前往「進階設定」啟用程式碼執行功能。Gemini API 可提供程式碼執行工具 函式呼叫:新增完成後 模型會決定何時使用程式碼
開始執行程式碼
您也可以使用程式碼執行筆記本:
前往 ai.google.dev 查看 | 試用 Colab 筆記本 | 在 GitHub 中查看筆記本 |
本節假設您已安裝 Gemini SDK 並設定 API 金鑰,如快速入門導覽課程所示。
允許在模型上執行程式碼
您可以在模型上啟用程式碼執行功能,如下所示:
import os
import google.generativeai as genai
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(
model_name='gemini-1.5-pro',
tools='code_execution')
response = model.generate_content((
'What is the sum of the first 50 prime numbers? '
'Generate and run code for the calculation, and make sure you get all 50.'))
print(response.text)
輸出內容可能如下所示:
```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}") ``` **Explanation:** 1. **`is_prime(n)` Function:** - Takes an integer `n` as input. - Returns `False` for numbers less than or equal to 1 (not prime). - Iterates from 2 up to the square root of `n`. If `n` is divisible by any number in this range, it's not prime, and we return `False`. - If the loop completes without finding a divisor, the number is prime, and we return `True`. 2. **`sum_of_primes(n)` Function:** - Takes an integer `n` (number of primes desired) as input. - Initializes an empty list `primes` to store the prime numbers. - Starts a loop, iterating through numbers starting from 2. - For each number `i`, it checks if it's prime using the `is_prime()` function. - If `i` is prime, it's appended to the `primes` list. - The loop continues until the `primes` list has `n` prime numbers. - Finally, it calculates and returns the sum of all the prime numbers in the `primes` list. 3. **Main Part:** - Calls `sum_of_primes(50)` to get the sum of the first 50 prime numbers. - Prints the result. **Output:** ``` The sum of the first 50 prime numbers is: 5117 ```
在要求中啟用程式碼
或者,您也可以在呼叫 generate_content
時啟用程式碼執行:
import os
import google.generativeai as genai
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(model_name='gemini-1.5-pro')
response = model.generate_content(
('What is the sum of the first 50 prime numbers? '
'Generate and run code for the calculation, and make sure you get all 50.'),
tools='code_execution')
print(response.text)
在即時通訊中使用程式碼
您也可以在對話中使用程式碼執行功能。
import os
import google.generativeai as genai
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(model_name='gemini-1.5-pro',
tools='code_execution')
chat = model.start_chat()
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.'))
print(response.text)
程式碼執行與函式呼叫
程式碼執行與函式呼叫 類似功能:
- 程式碼執行可讓模型在 API 後端,以固定的獨立方式執行程式碼 環境。
- 函式呼叫可讓您在 您可任意指定環境
一般來說,如果程式碼可以處理
確認是否屬於此情況程式碼執行更簡單 (只要啟用),且會在
單一 GenerateContent
要求 (會產生單筆費用)。功能
呼叫需要額外的 GenerateContent
要求來傳回輸出
呼叫函式 (因而產生多次費用)。
在多數情況下,如果您有自己的函式,應使用函式呼叫 以便在本機執行,而且如果需要 可編寫及執行 Python 程式碼的 API,然後傳回結果。
帳單
從 或 Gemini API 整合。系統會按照目前的輸入和輸出費率向您收費 符記。
以下是程式碼執行費用的其他注意事項:
- 只需針對傳遞至模型的輸入符記支付一次費用 系統只會向您收取模型傳回的最終輸出符記費用。
- 系統會將代表產生的代碼的權杖計為輸出權杖。
- 程式碼執行結果也會計為輸出符記。
限制
- 模型只能產生及執行程式碼。無法傳回其他構件 例如媒體檔案
- 這項功能不支援檔案 I/O,或是涉及非文字輸出的用途 (例如資料圖表或上傳的 CSV 檔案)。
- 程式碼在逾時前最多可執行 30 秒。
- 在某些情況下,啟用程式碼執行功能可能導致其他區域發生迴歸問題 例如寫故事
- 不同模型使用程式碼的方式可能有所不同 成功執行。Gemini 1.5 Pro 的表現最優異