Gemini Code Execution API 完全ガイド — AIにコードを書かせて実行する
背景と前提
Gemini Code Execution APIは、AIが生成したPythonコードを安全に実行できる革新的な機能です。従来は「AIが数学問題を解く」といえば、テキストベースの説明だけでしたが、このAPIを使うと、AIが実際にコードを書いて実行し、その結果をリアルタイムで取得できます。
データ分析、複雑な計算、シミュレーション、画像処理など、計算集約的なタスクをAIに任せることで、開発の効率化と精度向上が実現します。ここで整理するのは実装からベストプラクティスまで、全てを解説します。
Code Execution APIとは
基本的な仕組み
Code Execution APIは、以下のフローで動作します:
- ユーザーが問題や要件をAIに提示
- AIが解決方法をPythonコードで生成
- GoogleのセキュアなSandbox環境でコードが実行
- 実行結果がユーザーに返される
- AIがその結果を解釈して説明を提供
このプロセス全体がAPIを通じてシームレスに動作するため、開発者は複雑なコード実行管理を気にする必要がありません。
対応環境と制限事項
Code Executionは以下の環境で利用可能です:
- 対応言語: Python(現在のところPythonのみ対応)
- 実行環境: GoogleのセキュアなSandbox
- 実行時間制限: 1リクエストあたり最大90秒
- メモリ上限: 1GBまで
- ネットワーク: 外部への通信は不可(セキュリティ考慮)
セットアップと基本的な使い方
SDKのインストール
pip install google-genai
基本的なCode Executionの実装
最もシンプルなCode Execution APIの使用例を見てみましょう:
from google import genai
import os
# APIキーの設定
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
# Code Executionを有効にしたリクエスト
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[{
"role": "user",
"parts": [{
"text": "10から100までの素数を全て求めて、その個数と合計を教えてください"
}]
}],
tools=[{"google_search": {}}, {"code_execution": {}}]
)
# 結果の表示
for part in response.content.parts:
if hasattr(part, 'text'):
print("AI応答:", part.text)
elif hasattr(part, 'executable_code'):
print("実行されたコード:", part.executable_code.code)
elif hasattr(part, 'code_execution_result'):
print("実行結果:", part.code_execution_result.output)
実行結果:
実行されたコード:
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
primes = [n for n in range(10, 101) if is_prime(n)]
print(f"10から100までの素数: {primes}")
print(f"個数: {len(primes)}")
print(f"合計: {sum(primes)}")
実行結果:
10から100までの素数: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
個数: 21
合計: 1043
実践的な使用シーン
データ分析とグラフ生成
データ分析はCode Executionの最も実用的なユースケースです。複雑な計算とビジュアライゼーションをAIに任せられます:
from google import genai
import os
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
# 複雑なデータ分析タスク
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[{
"role": "user",
"parts": [{
"text": """
以下の売上データを分析してください:
- 2024年Q1: 150万円、Q2: 180万円、Q3: 165万円、Q4: 210万円
次の情報を計算してください:
1. 四半期ごとの成長率(前期比)
2. 平均売上と標準偏差
3. 最も好調な四半期と最低の四半期
4. 年間売上の合計と平均
"""
}]
}],
tools=[{"code_execution": {}}]
)
# 結果の表示
for part in response.content.parts:
if hasattr(part, 'code_execution_result'):
print(part.code_execution_result.output)
複雑な数学計算と統計
統計分析や数値計算も、Code Executionで精度高く実現できます:
# フィボナッチ数列と黄金比の関係を分析
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[{
"role": "user",
"parts": [{
"text": """
フィボナッチ数列の最初の30項を生成し、
連続する2つの項の比率から黄金比への収束を確認してください。
小数第10位まで表示してください。
"""
}]
}],
tools=[{"code_execution": {}}]
)
高度な活用テクニック
マルチターンでのCode Execution
複数のターンにわたるインタラクティブな分析も可能です:
from google import genai
import os
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
# マルチターン会話でCode Executionを活用
messages = [
{
"role": "user",
"parts": [{
"text": "正規分布に従う100個のランダムデータを生成してください"
}]
}
]
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=messages,
tools=[{"code_execution": {}}]
)
# AIの応答を表示
print("1ターン目:")
for part in response.content.parts:
if hasattr(part, 'text'):
print(part.text)
# 2ターン目:データの平均と分散を計算
messages.append({
"role": "model",
"parts": response.content.parts
})
messages.append({
"role": "user",
"parts": [{
"text": "このデータの平均値、分散、標準偏差、歪度を計算してください"
}]
})
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=messages,
tools=[{"code_execution": {}}]
)
print("\n2ターン目:")
for part in response.content.parts:
if hasattr(part, 'text'):
print(part.text)
出力例:
1ターン目:
実行されたコード:
import numpy as np
np.random.seed(42)
data = np.random.normal(loc=50, scale=15, size=100)
print(f"生成されたデータ(最初の10個): {data[:10]}")
print(f"全データ数: {len(data)}")
実行結果:
生成されたデータ(最初の10個): [53.24 47.35 62.48 45.12 ...]
全データ数: 100
2ターン目:
実行されたコード:
from scipy import stats
mean = np.mean(data)
variance = np.var(data)
std_dev = np.std(data)
skewness = stats.skew(data)
print(f"平均値: {mean:.4f}")
print(f"分散: {variance:.4f}")
print(f"標準偏差: {std_dev:.4f}")
print(f"歪度: {skewness:.4f}")
実行結果:
平均値: 50.2341
分散: 224.5623
標準偏差: 14.9854
歪度: 0.1523
エラーハンドリングとリトライロジック
Code Executionが失敗する場合もあります。堅牢な実装にはエラーハンドリングが必須です:
from google import genai
import os
from google.api_core import exceptions
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
def execute_code_safely(prompt, max_retries=3):
"""エラーハンドリング付きCode Execution"""
for attempt in range(max_retries):
try:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[{"role": "user", "parts": [{"text": prompt}]}],
tools=[{"code_execution": {}}]
)
return response
except exceptions.DeadlineExceeded:
print(f"タイムアウト (試行 {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
continue
else:
raise
except Exception as e:
print(f"エラー発生: {type(e).__name__}: {str(e)}")
raise
# 使用例
try:
result = execute_code_safely("1から1000までの数値で、各数字の出現回数を数えてください")
print(result)
except Exception as e:
print(f"処理失敗: {e}")
関連記事との連携
Code Execution APIは他のGemini APIの機能と組み合わせるとさらに強力になります。例えば:
- Gemini API クイックスタートで基本的なAPI連携を学ぶ
- Function Callingと組み合わせて、関数呼び出しとコード実行を統合
- ストリーミング & チャットでリアルタイムなコード実行結果の配信
ベストプラクティス
1. セキュリティを意識した設計
# ❌ 悪い例:ユーザー入力をそのまま使用
user_input = request.get("prompt")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=user_input,
tools=[{"code_execution": {}}]
)
# ✅ 良い例:入力の検証とサニタイズ
def sanitize_prompt(prompt):
# 入力の長さチェック
if len(prompt) > 5000:
raise ValueError("プロンプトが長すぎます")
# 危険なキーワードのチェック
dangerous_keywords = ["import os", "exec(", "eval("]
for keyword in dangerous_keywords:
if keyword.lower() in prompt.lower():
raise ValueError(f"不許可のコマンドが含まれています: {keyword}")
return prompt.strip()
user_input = request.get("prompt")
try:
safe_prompt = sanitize_prompt(user_input)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=safe_prompt,
tools=[{"code_execution": {}}]
)
except ValueError as e:
return {"error": str(e)}
2. レート制限とクォータ管理
import time
from functools import wraps
class RateLimiter:
def __init__(self, calls_per_minute=60):
self.calls_per_minute = calls_per_minute
self.calls = []
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
now = time.time()
# 1分以内のコールを記録
self.calls = [call_time for call_time in self.calls if now - call_time < 60]
if len(self.calls) >= self.calls_per_minute:
sleep_time = 60 - (now - self.calls[0])
print(f"レート制限に達しました。{sleep_time:.1f}秒待機します")
time.sleep(sleep_time)
self.calls.append(now)
return func(*args, **kwargs)
return wrapper
@RateLimiter(calls_per_minute=30)
def call_code_execution(prompt):
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
tools=[{"code_execution": {}}]
)
return response
3. 結果のキャッシング
import hashlib
import json
from datetime import datetime, timedelta
class ExecutionCache:
def __init__(self, ttl_minutes=60):
self.cache = {}
self.ttl = timedelta(minutes=ttl_minutes)
def _get_cache_key(self, prompt):
return hashlib.md5(prompt.encode()).hexdigest()
def get(self, prompt):
key = self._get_cache_key(prompt)
if key in self.cache:
cached_result, timestamp = self.cache[key]
if datetime.now() - timestamp < self.ttl:
return cached_result
else:
del self.cache[key]
return None
def set(self, prompt, result):
key = self._get_cache_key(prompt)
self.cache[key] = (result, datetime.now())
cache = ExecutionCache(ttl_minutes=30)
def cached_execute(prompt):
# キャッシュを確認
cached = cache.get(prompt)
if cached:
print("キャッシュから返却します")
return cached
# キャッシュにない場合は実行
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
tools=[{"code_execution": {}}]
)
cache.set(prompt, response)
return response
個人開発者の視点から(実体験メモ)
ここまでの要点
Gemini Code Execution APIは、計算集約的なタスクをAIに任せる強力なツールです。データ分析、複雑な計算、統計処理など、従来は開発者が自分でコードを書く必要があったタスクを、AIが自動生成・実行するコードで効率的に解決できます。
セキュリティを念頭に、入力検証とエラーハンドリングを適切に実装することで、本番環境でも安全に活用できます。他のGemini APIの機能と組み合わせることで、さらに高度なAI活用が実現します。