有了 Gemini API 的程式碼執行功能,模型可生成及執行 Python 程式碼,並根據結果反覆學習,直到生成最終輸出內容。您可以使用這個程式碼執行功能,建構應用程式來生成文字輸出內容,並在其中運用以程式碼為基礎的推理技術。舉例來說,您可以在應用程式中使用程式碼執行功能,解開方程式或處理文字。
Gemini API 提供程式碼執行工具,類似於函式呼叫。將程式碼執行功能新增為工具後,模型會決定何時使用這項工具。
支援的模型
限制
- 這項功能不支援檔案輸入/輸出。
- 程式碼執行作業最多可執行 30 秒,之後就會逾時。
語法範例
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ ... }], "tools": [{ "code_execution": {} }] }'
參數清單
如需實作詳情,請參閱範例。
Python
如要啟用程式碼執行作業,請在要求中指定程式碼執行作業 tool
。
CodeExecution
執行模型產生的程式碼,並自動將結果傳回模型。另請參閱 ExecutableCode 和 CodeExecutionResult,這是這項工具的輸入和輸出內容。
Part
| 選用:
模型產生的程式碼,用於執行。 |
| 選用:
執行 [ExecutableCode] 的結果。 |
ExecutableCode
| 必要項目:
產生的 支援:
|
| 必要項目:
要執行的程式碼。 |
CodeExecutionResult
| 必要項目:
程式碼執行結果。 可能的結果:
|
| 必要項目:
如果程式碼執行成功,則包含 |
範例
以下插圖說明如何將查詢和函式宣告提交至模型。
基本用途
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ "role": "user", "parts": [{ "text": "Calculate 20th fibonacci number. Then find the nearest palindrome to it." }] }], "tools": [{'codeExecution': {}}], }'
Python
from google import genai from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig client = genai.Client() model_id = "gemini-2.0-flash-001" 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, ), ) for part in response.candidates[0].content.parts: if part.executable_code: print(part.executable_code) if part.code_execution_result: print(part.code_execution_result) # Example response: # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='The 20th Fibonacci number is: 6765\n' # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='Lower Palindrome: 6666\nHigher Palindrome: 6776\nNearest Palindrome to 6765: 6776\n'
啟用模型上的程式碼執行功能
如要啟用基本程式碼執行功能,請參閱「程式碼執行」。
後續步驟
- 進一步瞭解 Gemini API。
- 進一步瞭解函式呼叫。
- 進一步瞭解如何使用 Gemini 產生內容。