Gemini API のコード実行機能を使用すると、モデルは Python コードを生成して実行し、最終的な出力に到達するまで結果から反復的に学習できます。このコード実行機能を使用すると、コードベースの推論を活用し、テキスト出力を生成するアプリケーションを構築できます。たとえば、方程式を解くアプリケーションやテキストを処理するアプリケーションでコード実行を使用できます。
Gemini API は、関数呼び出しと同様に、コード実行をツールとして提供します。コード実行をツールとして追加すると、モデルがコード実行を使用するタイミングを決定します。
サポートされているモデル
制限事項
- この機能はファイル I/O をサポートしていません。
- コード実行は、タイムアウトするまで最大 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 によるコンテンツ生成をご覧ください。