Antigravity を Python から使う方法はいくつかありますが、2026年現在、最も推奨される方法は google-genai SDK です。以前の google-generativeai から一新され、型安全性とインターフェースが大幅に改善されました。
このガイドでは、インストールから実際のコードまで、できるだけ短い手順でAntigravityを動かす方法を紹介します。
インストールと初期設定
pip install google-genaiAPIキーの設定
from google import genai
# 環境変数から読み込む(推奨)
import os
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
# または直接設定(本番環境では非推奨)
# client = genai.Client(api_key="YOUR_GOOGLE_API_KEY")APIキーは Google AI Studio から取得できます。
基本的なテキスト生成
from google import genai
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
# 最もシンプルな呼び出し
response = client.models.generate_content(
model="gemma-4-antigravity",
contents="Pythonで書いた初めてのプログラムを教えてください"
)
print(response.text)システム指示の設定
from google.genai import types
response = client.models.generate_content(
model="gemma-4-antigravity",
config=types.GenerateContentConfig(
system_instruction="あなたはPythonの専門家です。コードの説明は常に簡潔にしてください。",
temperature=0.7,
max_output_tokens=1024
),
contents="asyncioとは何ですか?"
)
print(response.text)チャット(マルチターン会話)
from google import genai
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
# チャットセッションの開始
chat = client.chats.create(
model="gemma-4-antigravity",
config=types.GenerateContentConfig(
system_instruction="あなたはコードレビューのエキスパートです。",
temperature=0.3
)
)
# 会話の継続
messages = [
"この関数のレビューをお願いします:\ndef calc(x, y):\n return x + y",
"型ヒントを追加するとしたらどう書きますか?",
"テストコードも書いてもらえますか?"
]
for user_msg in messages:
response = chat.send_message(user_msg)
print(f"User: {user_msg[:50]}...")
print(f"AI: {response.text[:200]}...\n")ストリーミング
長い回答を待たずにリアルタイムで表示します。
# ストリーミングテキスト生成
for chunk in client.models.generate_content_stream(
model="gemma-4-antigravity",
contents="Pythonのデータクラスについて詳しく説明してください"
):
print(chunk.text, end="", flush=True)
print() # 改行
# チャットでのストリーミング
chat = client.chats.create(model="gemma-4-antigravity")
for chunk in chat.send_message_stream("設計パターンのFactoryパターンを説明してください"):
print(chunk.text, end="", flush=True)
print()マルチモーダル(画像 + テキスト)
import PIL.Image
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
# ローカル画像ファイルを使う
image = PIL.Image.open("screenshot.png")
response = client.models.generate_content(
model="gemma-4-antigravity",
contents=[
image,
"このスクリーンショットのUIデザインの問題点を指摘してください"
]
)
print(response.text)
# 複数画像の比較
image1 = PIL.Image.open("before.png")
image2 = PIL.Image.open("after.png")
response = client.models.generate_content(
model="gemma-4-antigravity",
contents=[
"以下の2つのデザインを比較してください:",
"【変更前】", image1,
"【変更後】", image2
]
)
print(response.text)構造化出力(JSON)
import json
from google.genai import types
response = client.models.generate_content(
model="gemma-4-antigravity",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema={
"type": "object",
"properties": {
"title": {"type": "string"},
"summary": {"type": "string"},
"tags": {"type": "array", "items": {"type": "string"}},
"difficulty": {"type": "string", "enum": ["beginner", "intermediate", "advanced"]}
},
"required": ["title", "summary", "tags", "difficulty"]
}
),
contents="Pythonのデコレーターについての記事のメタデータを生成してください"
)
metadata = json.loads(response.text)
print(f"タイトル: {metadata['title']}")
print(f"タグ: {', '.join(metadata['tags'])}")
print(f"難易度: {metadata['difficulty']}")非同期処理
import asyncio
from google import genai
async def parallel_requests(prompts: list[str]) -> list[str]:
"""複数のリクエストを並列実行"""
client = genai.AsyncClient(api_key=os.environ["GOOGLE_API_KEY"])
async def _request(prompt: str) -> str:
response = await client.aio.models.generate_content(
model="gemma-4-antigravity",
contents=prompt
)
return response.text
results = await asyncio.gather(*[_request(p) for p in prompts])
return results
# 実行
async def main():
prompts = [
"Pythonのリスト内包表記とは?",
"ジェネレーターとは何ですか?",
"デコレーターの使い方を教えてください"
]
results = await parallel_requests(prompts)
for prompt, result in zip(prompts, results):
print(f"Q: {prompt}\nA: {result[:100]}...\n")
asyncio.run(main())エラーハンドリング
from google import genai
from google.api_core import exceptions as google_exceptions
def safe_generate(client, model: str, contents, max_retries: int = 3) -> str:
"""エラーハンドリング付きの生成関数"""
for attempt in range(max_retries):
try:
response = client.models.generate_content(
model=model,
contents=contents
)
return response.text
except google_exceptions.ResourceExhausted:
# レート制限
import time
wait_time = 2 ** attempt
print(f"レート制限。{wait_time}秒後に再試行...")
time.sleep(wait_time)
except google_exceptions.InvalidArgument as e:
# 入力エラー(リトライ不可)
print(f"入力が無効です: {e}")
raise
except google_exceptions.ServiceUnavailable:
# サービス一時停止
if attempt < max_retries - 1:
import time
time.sleep(5)
else:
raise
raise RuntimeError(f"{max_retries}回のリトライ後も失敗しました")トークン数の確認
# 送信前にトークン数を確認
token_count = client.models.count_tokens(
model="gemma-4-antigravity",
contents="長いプロンプトのテキストをここに入れます..."
)
print(f"入力トークン数: {token_count.total_tokens}")
# 使用量の確認(送信後)
response = client.models.generate_content(
model="gemma-4-antigravity",
contents="こんにちは"
)
if response.usage_metadata:
print(f"入力: {response.usage_metadata.prompt_token_count} tokens")
print(f"出力: {response.usage_metadata.candidates_token_count} tokens")全体を振り返って:使い始めるための3ステップ
pip install google-genaiでインストール- Google AI Studio で API キーを取得して環境変数に設定
client.models.generate_content(model="gemma-4-antigravity", contents="...")で呼び出す
google-genai SDK は以前の google-generativeai に比べてインターフェースが整理されており、型補完も効きやすくなっています。新規プロジェクトではこちらを使うことをおすすめします。
詳細な API リファレンスは Google AI ドキュメント で確認できます。
個人開発12年の現場で実感したこと
線引きするときの3つの判断軸
- 失敗時の影響が金銭やユーザー体験にどれだけ波及するか
- 復旧オペレーションが明文化されているか
- 観測ログから人間が再現できる粒度に整っているか
個人開発12年とアーティスト活動から見るエージェント設計
線引きするときの3つの判断軸
- 失敗時の影響が金銭やユーザー体験にどれだけ波及するか
- 復旧オペレーションが明文化されているか
- 観測ログから人間が再現できる粒度に整っているか
まとめ — 検証ステップの推奨
- 観測メトリクスとアラートを設置
- 限定ロールアウトで本番検証