使用 Gemini API 執行程式碼

有了 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

執行模型產生的程式碼,並自動將結果傳回模型。另請參閱 ExecutableCodeCodeExecutionResult,這是這項工具的輸入和輸出內容。

Part

executable_code

選用: ExecutableCode

模型產生的程式碼,用於執行。
請參閱「程式碼執行作業」[API]。

code_execution_result

選用: CodeExecutionResult

執行 [ExecutableCode] 的結果。
請參閱「程式碼執行作業」[API]。

ExecutableCode

language

必要項目: string (enum)

產生的 code 支援的程式設計語言。


支援:
  • PYTHON

code

必要項目: string

要執行的程式碼。
請參閱「程式碼執行作業」[API]。

CodeExecutionResult

outcome

必要項目: string (enum)

程式碼執行結果。


可能的結果:
  • 程式碼執行完畢。(OUTCOME_OK)
  • 程式碼執行完畢,但失敗。stderr 應包含原因。(OUTCOME_FAILED)
  • 程式碼執行時間過長,已取消執行作業。部分輸出內容可能會出現,(OUTCOME_DEADLINE_EXCEEDED)

output

必要項目: string

如果程式碼執行成功,則包含 stdout;如果失敗,則包含 stderr 或其他說明。
請參閱「程式碼執行作業」[API]。

範例

以下插圖說明如何將查詢和函式宣告提交至模型。

基本用途

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'

啟用模型上的程式碼執行功能

如要啟用基本程式碼執行功能,請參閱「程式碼執行」。

後續步驟