取り組みの背景 — この記事シリーズについて
このシリーズは、Gemini Lab のプレミアム会員向けコンテンツから得られた知見を、無料・有料両方のユーザーに実用的な形で提供する試みです。
前編の目的: Gemini API を実際のプロジェクトに組み込むための基本スキルを習得 後編の目的: 本番グレードのシステム構築、音声 AI、収益化パイプライン
このガイドは Python 3.10+ を前提としていますが、REST API の概念は言語に依らず応用可能です。
Gemini API の基本設計パターン
テキスト生成の基本構造
最小限の実装から始めます:
import google.generativeai as genai
import os
# API キーの設定
api_key = os.getenv("GEMINI_API_KEY")
genai.configure(api_key=api_key)
# モデルの初期化
model = genai.GenerativeModel("gemini-2.5-pro")
# シンプルなテキスト生成
response = model.generate_content("日本の経済成長率を 3 文で説明してください")
print(response.text)ポイント:
GenerativeModelでモデルを指定("gemini-2.5-pro"、"gemini-2.5-flash" など)generate_content()にプロンプトを渡すだけで実行- 応答は
response.textで文字列として取得
より詳細な設定
実際のプロジェクトでは、以下のパラメータを制御します:
from google.generativeai.types import GenerationConfig, SafetySetting, HarmCategory, HarmBlockThreshold
response = model.generate_content(
contents="Python で Web API を設計する際のベストプラクティスは?",
generation_config=GenerationConfig(
temperature=0.7, # 創造性(0.0~2.0)
top_p=0.95, # 多様性制御
top_k=40, # 候補の絞り込み
max_output_tokens=1024, # 応答の最大トークン数
stop_sequences=["---"], # 出力終了トリガー
),
safety_settings=[
SafetySetting(
category=HarmCategory.HARM_CATEGORY_UNSPECIFIED,
threshold=HarmBlockThreshold.BLOCK_NONE,
)
]
)
print(response.text)パラメータの解説:
- temperature: 0 に近いほど決定的、2 に近いほどランダム。通常は 0.5~0.9
- top_p: 核サンプリング。高確率な選択肢に絞り込む。通常は 0.8~0.95
- max_output_tokens: API のトークン制限内で設定。1024~100000
ストリーミング応答の実装
長い応答は部分的に返してユーザー体験を向上させます:
model = genai.GenerativeModel("gemini-2.5-pro")
# ストリーミングを有効化
response = model.generate_content(
contents="AI の歴史を 1000 単語で説明してください",
stream=True
)
# テキストを部分的に出力
for chunk in response:
if chunk.text:
print(chunk.text, end="", flush=True)
print() # 改行活用例:
Web アプリケーションで Server-Sent Events (SSE) 経由でクライアントにリアルタイム配信。ユーザーは AI が「考えている」過程を見ることができます。
マルチターン会話の管理
複数の質問・回答を一つの会話として管理します:
model = genai.GenerativeModel("gemini-2.5-pro")
# チャット履歴の初期化
chat = model.start_chat(history=[])
# 1 ターン目
user_input_1 = "Python で非同期プログラミングについて教えてください"
response_1 = chat.send_message(user_input_1)
print(f"User: {user_input_1}")
print(f"AI: {response_1.text}\n")
# 2 ターン目(前の応答を参照可能)
user_input_2 = "asyncio.gather() の使用例を 3 つ挙げてください"
response_2 = chat.send_message(user_input_2)
print(f"User: {user_input_2}")
print(f"AI: {response_2.text}\n")
# 3 ターン目
user_input_3 = "その中で最も実用的なのはどれですか?"
response_3 = chat.send_message(user_input_3)
print(f"User: {user_input_3}")
print(f"AI: {response_3.text}\n")重要: 会話コンテキストは model.start_chat() で自動管理されます。各ターンを history に追加する手動作業は不要です。
Function Calling の基本
Function Calling により、AI が必要に応じて外部ツール(API、データベース、計算関数)を呼び出せます。
ツール定義と呼び出しパターン
import json
# ツール(関数)の定義
tools = [
{
"name": "get_product_info",
"description": "商品 ID から商品情報(価格、在庫)を取得",
"input_schema": {
"type": "object",
"properties": {
"product_id": {
"type": "string",
"description": "商品 ID(例:PROD-12345)"
},
"include_reviews": {
"type": "boolean",
"description": "レビュー情報を含めるか(デフォルト:false)"
}
},
"required": ["product_id"]
}
},
{
"name": "update_inventory",
"description": "在庫数を更新",
"input_schema": {
"type": "object",
"properties": {
"product_id": {"type": "string"},
"quantity_change": {"type": "integer", "description": "増減量"}
},
"required": ["product_id", "quantity_change"]
}
}
]
# 実際のツール実装
def get_product_info(product_id: str, include_reviews: bool = False) -> dict:
"""実際のビジネスロジック"""
products_db = {
"PROD-001": {"name": "ノート PC", "price": 150000, "stock": 5},
"PROD-002": {"name": "マウス", "price": 3000, "stock": 50},
}
if product_id not in products_db:
return {"error": "商品が見つかりません"}
info = products_db[product_id]
if include_reviews:
info["reviews"] = "平均 4.5 星(100 件)"
return info
def update_inventory(product_id: str, quantity_change: int) -> dict:
"""在庫更新(実際はデータベース操作)"""
return {"status": "success", "product_id": product_id, "change": quantity_change}
# API 呼び出し
model = genai.GenerativeModel(
"gemini-2.5-pro",
tools=tools
)
# ユーザーリクエスト
user_message = "PROD-001 の在庫を 3 個減らして、最新情報を教えてください"
response = model.generate_content(user_message)
# Function Calling の結果を処理
for content_part in response.content:
if hasattr(content_part, 'function_call'):
# AI が呼び出したい関数を取得
func_call = content_part.function_call
func_name = func_call.name
func_args = {k: v for k, v in func_call.args.items()}
print(f"AI が '{func_name}' を呼び出しました:{func_args}")
# 実際の関数を実行
if func_name == "get_product_info":
result = get_product_info(**func_args)
elif func_name == "update_inventory":
result = update_inventory(**func_args)
else:
result = {"error": "未知の関数"}
print(f"実行結果:{result}")
# 結果を AI に返す
second_response = model.generate_content([
user_message,
response,
{"role": "user", "parts": [{"text": f"関数実行結果:{json.dumps(result)}"}]}
])
print(f"AI の最終回答:{second_response.text}")フロー図:
ユーザー
↓
AI(関数呼び出しが必要と判断)
↓
関数定義と引数を指定
↓
アプリケーション(実際の関数実行)
↓
実行結果を AI に返す
↓
AI(結果を文脈に組み込んで回答)
↓
ユーザー
構造化出力(responseSchema)の活用
AI の応答を常に JSON 形式で取得したい場合:
from google.generativeai.types import ResponseSchema, GenerateContentResponse
# 出力スキーマを定義
schema = [
ResponseSchema(
name="analysis_result",
description="分析結果",
type="object",
properties=[
ResponseSchema(name="title", description="タイトル", type="string"),
ResponseSchema(name="summary", description="要約(200 字以内)", type="string"),
ResponseSchema(
name="key_points",
description="重要なポイント",
type="array",
items=ResponseSchema(name="point", type="string")
),
ResponseSchema(name="confidence", description="確信度(0~100)", type="integer")
]
)
]
model = genai.GenerativeModel(
"gemini-2.5-pro",
generation_config=GenerationConfig(
response_mime_type="application/json",
response_schema=schema,
)
)
prompt = """
以下のテキストを分析してください:
「AI 技術は医療分野で診断精度を向上させ、
製造業では異常検知を自動化し、
金融では不正検出を強化しています」
"""
response = model.generate_content(prompt)
# JSON として直接パース可能
import json
result = json.loads(response.text)
print(json.dumps(result, indent=2, ensure_ascii=False))出力例:
{
"analysis_result": {
"title": "AI の実社会への応用範囲",
"summary": "AI は医療診断、製造異常検知、金融不正検出など複数の産業で実用化され、各分野で具体的な価値を生み出している。",
"key_points": [
"医療:診断精度の向上",
"製造:異常検知の自動化",
"金融:不正検出の強化"
],
"confidence": 95
}
}マルチモーダル入力の基礎
画像分析の基本
from pathlib import Path
# ローカル画像ファイルを読み込み
image_path = Path("screenshot.png")
image_data = image_path.read_bytes()
# ファイル MIME タイプの特定
import mimetypes
mime_type, _ = mimetypes.guess_type(str(image_path))
# Gemini に送信
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content([
"この画像に写っているものを詳しく説明してください。テキストがあれば日本語に翻訳してください。",
{
"mime_type": mime_type,
"data": image_data
}
])
print(response.text)サポート形式:
- 画像:PNG、JPEG、GIF、WebP
- 動画:MP4、MPEG、MOV、AVI、FLV、MKV、WMV、WEBM(25MB 以下)
- 音声:WAV、MP3、AIFF、AAC、OGG、FLAC
PDF ドキュメント処理
import mimetypes
# PDF をアップロード
pdf_path = "technical_report.pdf"
with open(pdf_path, "rb") as pdf_file:
pdf_data = pdf_file.read()
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content([
{
"mime_type": "application/pdf",
"data": pdf_data
},
"このドキュメントから以下の情報を抽出してください:\n1. 主なテーマ\n2. 著者\n3. 重要な結論\n4. 参考文献の数"
])
print(response.text)ポイント:
- PDF は最大 100 万トークン(全ページ)まで一括処理
- テーブル・グラフも認識可能
- OCR が必要な画像スキャン PDF にも対応
100万トークンコンテキストの使い方
大規模ファイル複数の分析:
import os
from pathlib import Path
# 複数の PDF をロード
pdf_files = list(Path("documents/").glob("*.pdf"))
contents = []
# プロンプトを先頭に追加
contents.append({
"text": """以下の 3 つの技術レポートを統合分析してください:
1. 全体の共通テーマを特定
2. 手法の相違点を列挙
3. 結論の矛盾点を指摘
4. 総合的な推奨事項を述べる"""
})
# すべての PDF を追加
for pdf_path in pdf_files[:3]: # 最初の 3 ファイル
with open(pdf_path, "rb") as f:
contents.append({
"mime_type": "application/pdf",
"data": f.read()
})
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content(contents)
print(response.text)実用例:
- 学位論文 5~10 本の比較分析
- 複数の学術論文から知見を統合
- 月報・年報の複数年度分を一括分析
- 法律文書の参照一貫性チェック
Google Workspace 連携のコツ
Docs での自動文書作成パターン
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
# Google Docs API で document を作成
docs_service = build('docs', 'v1', credentials=credentials)
drive_service = build('drive', 'v3', credentials=credentials)
# 新しいドキュメント作成
doc = docs_service.documents().create(body={'title': 'AI Report 2026'}).execute()
doc_id = doc['documentId']
# Gemini で本文を生成
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content(
"日本の AI 産業の現状と展望について、3000 字のレポートを書いてください。マークダウン形式で出力してください。"
)
# Gemini の出力を Docs に挿入
requests = [
{
'insertText': {
'text': response.text,
'location': {'index': 1}
}
}
]
docs_service.documents().batchUpdate(
documentId=doc_id,
body={'requests': requests}
).execute()
print(f"ドキュメント作成完了:https://docs.google.com/document/d/{doc_id}")Sheets でのデータ分析
# Google Sheets から データを読み込み
sheets_service = build('sheets', 'v4', credentials=credentials)
result = sheets_service.spreadsheets().values().get(
spreadsheetId='SHEET_ID',
range='Sheet1!A1:Z100'
).execute()
data = result.get('values', [])
# Gemini でデータを分析
model = genai.GenerativeModel("gemini-2.5-pro")
analysis = model.generate_content(f"""
以下の営業データを分析してください:
{data}
分析内容:
1. 売上トップ 3 の商品
2. 地域別の売上シェア
3. 前月比の変化率
4. 改善提案
""")
# 分析結果を Sheets に記録
sheets_service.spreadsheets().values().update(
spreadsheetId='SHEET_ID',
range='Analysis!A1',
valueInputOption='USER_ENTERED',
body={'values': [[analysis.text]]}
).execute()次のステップ — 後編(プレミアム)で学べること
前編では API の基本と初級テクニックを習得しました。後編では以下のトピックを深掘ります:
- 並列ツール呼び出し:複数の関数を同時実行でパフォーマンス向上
- Live API 音声処理:リアルタイム音声会話インターフェース
- 本番エージェント構築:Gemini 2.5 Pro を使った自律エージェント
- Vertex AI での ファインチューニング:ドメイン特化モデルの構築
- コンテキストキャッシング:大規模入力でコスト削減
- Veo 3 動画生成 API:テキストから動画を自動生成
- SaaS 収益化:Gemini API を使ったビジネスモデル
プレミアム記事では、実際の本番プロジェクトからの事例コード、パフォーマンス最適化のベストプラクティス、トラブルシューティングガイドを掲載予定です。
Gemini Lab コミュニティで次のステップについて詳しくご相談ください。