Gemini API は、モデルが Python コードを生成して実行できるようにするコード実行ツールを提供します。モデルは、最終的な出力に到達するまで、コード実行の結果から反復的に学習できます。コード実行を使用して、コードベースの推論を活用するアプリケーションを構築できます。たとえば、コード実行を使用して方程式を解いたり、テキストを処理したりできます。コード実行環境に含まれているライブラリを使用して、より専門的なタスクを実行することもできます。
Gemini は Python でのみコードを実行できます。Gemini に別の言語でコードを生成するよう依頼することはできますが、モデルはコード実行ツールを使用してコードを実行することはできません。
コード実行を有効にする
コード実行を有効にするには、モデルでコード実行ツールを構成します。これにより、モデルはコードを生成して実行できます。
Python
from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model="gemini-2.5-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)] ), ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output)
JavaScript
import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({}); let response = await ai.models.generateContent({ model: "gemini-2.5-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: { tools: [{ codeExecution: {} }], }, }); const parts = response?.candidates?.[0]?.content?.parts || []; parts.forEach((part) => { if (part.text) { console.log(part.text); } if (part.executableCode && part.executableCode.code) { console.log(part.executableCode.code); } if (part.codeExecutionResult && part.codeExecutionResult.output) { console.log(part.codeExecutionResult.output); } });
Go
package main import ( "context" "fmt" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } result, _ := client.Models.GenerateContent( ctx, "gemini-2.5-flash", genai.Text("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, ) fmt.Println(result.Text()) fmt.Println(result.ExecutableCode()) fmt.Println(result.CodeExecutionResult()) }
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d ' {"tools": [{"code_execution": {}}], "contents": { "parts": { "text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50." } }, }'
出力は次のようになります(読みやすくするために書式設定されています)。
Okay, I need to calculate the sum of the first 50 prime numbers. Here's how I'll approach this: 1. **Generate Prime Numbers:** I'll use an iterative method to find prime numbers. I'll start with 2 and check if each subsequent number is divisible by any number between 2 and its square root. If not, it's a prime. 2. **Store Primes:** I'll store the prime numbers in a list until I have 50 of them. 3. **Calculate the Sum:** Finally, I'll sum the prime numbers in the list. Here's the Python code to do this: def is_prime(n): """Efficiently checks if a number is prime.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True primes = [] num = 2 while len(primes) < 50: if is_prime(num): primes.append(num) num += 1 sum_of_primes = sum(primes) print(f'{primes=}') print(f'{sum_of_primes=}') primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229] sum_of_primes=5117 The sum of the first 50 prime numbers is 5117.
この出力は、コード実行時にモデルが返す複数のコンテンツ部分を組み合わせたものです。
text
: モデルによって生成されたインライン テキストexecutableCode
: 実行されることを想定してモデルによって生成されたコードcodeExecutionResult
: 実行可能コードの結果
これらの部分の命名規則は、プログラミング言語によって異なります。
チャットでコード実行を使用する
コード実行をチャットの一部として使用することもできます。
Python
from google import genai from google.genai import types client = genai.Client() chat = client.chats.create( model="gemini-2.5-flash", config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) response = chat.send_message("I have a math question for you.") print(response.text) 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." ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output)
JavaScript
import {GoogleGenAI} from "@google/genai"; const ai = new GoogleGenAI({}); const chat = ai.chats.create({ model: "gemini-2.5-flash", history: [ { role: "user", parts: [{ text: "I have a math question for you:" }], }, { role: "model", parts: [{ text: "Great! I'm ready for your math question. Please ask away." }], }, ], config: { tools: [{codeExecution:{}}], } }); const response = await chat.sendMessage({ 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." }); console.log("Chat response:", response.text);
Go
package main import ( "context" "fmt" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } chat, _ := client.Chats.Create( ctx, "gemini-2.5-flash", config, nil, ) result, _ := chat.SendMessage( ctx, genai.Part{Text: "What is the sum of the first 50 prime numbers? " + "Generate and run code for the calculation, and " + "make sure you get all 50.", }, ) fmt.Println(result.Text()) fmt.Println(result.ExecutableCode()) fmt.Println(result.CodeExecutionResult()) }
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"tools": [{"code_execution": {}}], "contents": [ { "role": "user", "parts": [{ "text": "Can you print \"Hello world!\"?" }] },{ "role": "model", "parts": [ { "text": "" }, { "executable_code": { "language": "PYTHON", "code": "\nprint(\"hello world!\")\n" } }, { "code_execution_result": { "outcome": "OUTCOME_OK", "output": "hello world!\n" } }, { "text": "I have printed \"hello world!\" using the provided python code block. \n" } ], },{ "role": "user", "parts": [{ "text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50." }] } ] }'
入出力(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 で送信できません。
- コード実行は、テキスト ファイルと CSV ファイルで最適に動作します。
- 入力ファイルは
part.inlineData
またはpart.fileData
(Files API を介してアップロード)で渡すことができ、出力ファイルは常にpart.inlineData
として返されます。
シングルターン | 双方向(Multimodal Live API) | |
---|---|---|
サポートされているモデル | Gemini 2.0 と 2.5 のすべてのモデル | Flash の試験運用版モデルのみ |
サポートされているファイル入力タイプ | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts |
サポートされているプロット ライブラリ | Matplotlib、seaborn | Matplotlib、seaborn |
マルチツールの使用 | 対応(コード実行とグラウンディングのみ) | はい |
課金
Gemini API からのコード実行を有効にしても、追加料金は発生しません。使用している Gemini モデルに基づいて、入力トークンと出力トークンの現在のレートで課金されます。
コード実行の課金に関するその他の注意事項は次のとおりです。
- モデルに渡す入力トークンに対しては一度だけ課金され、モデルから返される最終出力トークンに対して課金されます。
- 生成されたコードを表すトークンは、出力トークンとしてカウントされます。生成されたコードには、テキストとマルチモーダル出力(画像など)を含めることができます。
- コード実行の結果も出力トークンとしてカウントされます。
次の図に課金モデルを示します。
- 使用している Gemini モデルに基づいて、入力トークンと出力トークンの現在のレートで課金されます。
- Gemini がレスポンスの生成時にコード実行を使用する場合、元のプロンプト、生成されたコード、実行されたコードの結果には中間トークンというラベルが付けられ、入力トークンとして課金されます。
- Gemini は次に要約を生成し、生成されたコード、実行されたコードの結果、最終的な要約を返します。これらは出力トークンとして課金されます。
- Gemini API の API レスポンスには中間トークン数が含まれるため、最初のプロンプト以外の追加の入力トークンを取得する理由を把握できます。
制限事項
- モデルはコードの生成と実行のみが可能です。メディア ファイルなど、他のアーティファクトを返すことはできません。
- コード実行を有効にすると、モデル出力の他の領域(ストーリーの作成など)で回帰が発生することがあります。
- モデルによって、コード実行を成功させる能力にばらつきがあります。
サポートされているライブラリ
コード実行環境には、次のライブラリが含まれています。
- attrs
- チェス
- contourpy
- fpdf
- geopandas
- imageio
- jinja2
- joblib
- jsonschema
- jsonschema-specifications
- lxml
- matplotlib
- mpmath
- numpy
- opencv-python
- openpyxl
- パッケージ化
- pandas
- pillow
- protobuf
- pylatex
- pyparsing
- PyPDF2
- python-dateutil
- python-docx
- python-pptx
- reportlab
- scikit-learn
- scipy
- seaborn
- six
- striprtf
- sympy
- tabulate
- tensorflow
- toolz
- xlrd
独自のライブラリをインストールすることはできません。
次のステップ
- コード実行 Colab を試す。
- 他の Gemini API ツールについて学習します。