🌟 GCP AI学習カリキュラム:メインメニュー
このプロジェクトでは、GCP(Google Cloud Platform)のAI分野、特にVertex AIと生成AIを1日1時間の学習で習得することを目指します。
なお、初心者向けです。自分は AWS をメインとしています。
GCP は AWS のようにコミュニティが盛んではない印象であるため、とっつきにくかったのですが、AI 時代の世の中 GCP についても少しづつやっていこうという思いで作成しました。
📅 学習スケジュール概要
| フェーズ | タイトル | 期間 | 内容 |
|---|---|---|---|
| Phase 1 | GCPの基礎 | 1週間 | 環境構築、予算管理、コンソール操作 |
| Phase 2 | AIを体験する | 2週間 | Vertex AI Studio, プロンプト設計 |
| Phase 3 | AIアプリを作る (この記事) | 3週間 | Python SDK (VS Code), RAG, 実践アプリ |
| Phase 4 | AIのプロへ(次回) | 継続 | エージェント開発、チューニング、責任あるAI |
🛠 準備するもの
- Googleアカウント(Gmailなど)
- GCPプロジェクト(Phase 1で作成済みのもの)
- PC(VS Code, Pythonが動く環境)
🏗 Phase 3 詳細手順ガイド:AIアプリを作る(Python実践)
VS Code(ローカル環境)を使用して、Gemini APIをプロフェッショナルなワークフローで利用するためのガイドです。
※本ガイドは、最新の google-genai SDK(2026年以降の標準方式)に基づいています。
📅 Week 1: ローカル開発環境とSDKの基礎
目標: AI開発ができる環境を作る。
Day 1: VS Code環境構築
- Pythonインストール: 公式サイト から最新のPythonをインストール。
-
プロジェクト作成: 適当なフォルダ(
gemini-study)をVS Codeで開く。 -
仮想環境の作成: ターミナルで
python -m venv venvを実行。 -
gcloud CLIのインストール: Google Cloud SDK をインストールし、
gcloud initで初期設定。
Day 2: 認証(ADC) & 初回呼出
-
ADCの設定: ターミナルで
gcloud auth application-default loginを実行。ブラウザが開くので許可。 -
SDKインストール:
pip install google-genai -
Hello World:
main.pyを作成。
day2.py
from google import genai
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913" # あなたの実際のプロジェクトIDに書き換えてください
LOCATION = "us-central1"
# クライアントの初期化 (Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# テキスト生成
response = client.models.generate_content(
model="gemini-2.5-flash-lite", # 使用するモデルを指定
contents="こんにちは Vertex AI!"
)
# 結果表示
print(response.text)
Day 3: テキスト生成詳細
-
レスポンス構造:
responseオブジェクトの中身(candidates,usage_metadata)をprintして観察。
Day 2のコードに以下を追加して、レスポンスの詳細を確認します。
day3_1.py
# 追加の情報も表示
print(response.candidates)
print(response.usage_metadata)
-
Markdown出力: AIの回答を Markdown ファイル(
output.md)として保存するコードを書く。
day3_2.py
# 生成されたテキストをファイルに保存
with open("output.md", "w") as f:
f.write(response.text)
Day 4: ストリーミング実装
-
Streaming:
client.models.generate_content_streamを使用. -
リアルタイム表示:
for chunk in response:を使い、print(chunk.text, end="", flush=True)で文字が流れる演出を実装。
day4.py
from google import genai
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化(Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# ストリーミングでテキスト生成
response = client.models.generate_content_stream(
model="gemini-2.5-flash-lite",
contents="こんにちは Vertex AI!"
)
# リアルタイムで表示
for chunk in response:
print(chunk.text, end="", flush=True)
Day 5: チャットセッション(履歴管理)
-
状態保持:
chat = client.chats.create(model=...)を使用。 -
対話型CLI:
while True:ループを作成し、ターミナルでAIとチャットし続けられるプログラムを作成。
day5.py
from google import genai
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化(Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# チャットセッション開始
chat = client.chats.create(
model="gemini-2.5-flash-lite"
)
# 対話型CLI
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Exiting chat.")
break
response = chat.send_message(user_input)
print("AI:", response.text)
Day 6: マルチモーダル分析(ローカルファイル)
-
メディアの渡し方:
from google.genai import typesのPartを使用。 -
実装:
with open("image.jpg", "rb") as f:で画像を開き、AIに渡して説明させる。
day6.py
from google import genai
from google.genai import types
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化(Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# 画像ファイルをAIに渡す
with open("image.jpg", "rb") as f:
# 画像をPartオブジェクトに変換
image_part = types.Part.from_bytes(
data=f.read(),
mime_type="image/jpeg"
)
# AIに画像を渡して説明させる
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=image_part
)
# 結果表示
print(response.text)
Day 7: パラメータ制御 & 安全設定
-
GenerateConfig:
types.GenerateContentConfigを使用して、温度や最大トークン数を調整。 -
SafetySettings:
types.SafetySettingを設定し、特定のカテゴリの有害な内容をブロックする例を実装。
day7.py
from google import genai
from google.genai import types
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化(Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# パラメータ制御と安全設定の例
config = types.GenerateContentConfig(
temperature=0.9,
safety_settings=[
types.SafetySetting(
category='HARM_CATEGORY_HATE_SPEECH',
threshold='BLOCK_LOW_AND_ABOVE'
),
types.SafetySetting(
category='HARM_CATEGORY_DANGEROUS_CONTENT',
threshold='BLOCK_LOW_AND_ABOVE'
)
]
)
# テキスト生成
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="こんにちは Vertex AI!",
config=config
)
# 結果表示
print(response.text)
📅 Week 2: Grounding と高度な連携
目標: ローカル環境の機動性を活かし、外部知識やツールを統合する。
Day 8: Grounding (Google検索連携)
-
実践:
tools=[types.Tool(google_search_retrieval=types.GoogleSearchRetrieval())]を設定に追加。
day8.py
from google import genai
from google.genai import types
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化(Vertex AIモード)
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# Google検索ツールを追加してテキスト生成
config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())]
)
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="最新のAIニュースを教えてください。",
config=config
)
# 結果表示
print(response.text)
Day 9 & 10: Function Calling (関数の定義と実装)
- 定義: AIが呼び出せるPython関数を定義します。
-
実装: 自作関数を
toolsに渡し、AIが状況に応じて関数を呼び出し、その結果を元に回答するフローを実装します。
day9_10.py
from google import genai
from google.genai import types
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# AIが呼び出す関数の定義 (Day 9)
def get_current_stock(product_name: str) -> int:
"""指定された製品の現在の在庫数を返します。"""
# 実際にはここでDBやAPIを確認しますが、今回はデモ用に固定値を返します
stocks = {"laptop": 5, "smartphone": 12, "tablet": 0}
return stocks.get(product_name.lower(), 0)
# ツールとして関数を登録 (Day 10)
config = types.GenerateContentConfig(
tools=[get_current_stock]
)
# AIに在庫について質問
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="タブレット(tablet)の在庫はありますか?",
config=config
)
# 結果の表示
print(response.text)
Day 11: システム指示の活用
-
ロールプレイ:
system_instructionを設定し、AIの役割や振る舞いを固定します。
day11.py
from google import genai
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# システムプロンプトの設定
system_instruction = "あなたは熟練のGCPアーキテクトです。回答は常に簡潔に、技術的な正確さを重視して答えてください。"
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="Cloud Runのメリットを3つ教えて。",
config={'system_instruction': system_instruction}
)
print(response.text)
Day 12: エラーハンドリング & リトライ
-
堅牢化:
google.genai.errorsを用いた例外処理を実装し、API制限やネットワークエラーに対応します。
day12.py
from google import genai
from google.genai import errors
client = genai.Client(vertexai=True, project="my-ai-study-494913", location="us-central1")
try:
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="こんにちは!"
)
print(response.text)
except errors.ClientError as e:
print(f"クライアントエラー(認証やプロジェクト設定の不備): {e}")
except errors.ServerError as e:
print(f"サーバーエラー(GCP側の問題): {e}")
except Exception as e:
print(f"予期せぬエラー: {e}")
Day 13-14: 総復習と調整 (実践:ログ分析ツール)
- 課題: 「ローカルのログファイルを読み、異常があれば検索して解決策を提案する」統合ツールを作成します。
day13_14.py
from google import genai
from google.genai import types
# ダミーのログファイル作成
LOG_FILE = "app.log"
with open(LOG_FILE, "w") as f:
f.write("INFO: Application started\n")
f.write("ERROR: Connection failed to database - Error Code 5003\n")
# 環境変数の設定
PROJECT_ID = "my-ai-study-494913"
LOCATION = "us-central1"
# クライアントの初期化
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION
)
# 1. ログの読み込み
with open(LOG_FILE, "r") as f:
log_content = f.read()
# 2. Google検索(Grounding)を有効にした設定
config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
system_instruction="あなたはシステム管理者です。提供されたログからエラーを特定し、その解決策を最新の情報を元に提案してください。"
)
# 3. AIによる分析と提案
print("--- ログ分析中 ---")
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=f"以下のログを分析して、エラーの解決策を教えてください:\n\n{log_content}",
config=config
)
# 4. 結果表示
print(response.text)
📅 Week 3: 実践アプリ開発
目標: 1つの完結したツールを形にする。
Day 15-21: アプリ開発 (AI インフラ・モニター)
目標: 1つの完結したツールを形にする。
-
JSON出力:
response_mime_type="application/json"を活用。 - 外部通知: 最終結果を Slack や Discord に投稿。
-
仕上げ: ログ出力、設定の外部ファイル化(
.env)を行い、ツールとしての完成度を高めます。
1. 設定ファイル (.env)
.env
GCP_PROJECT_ID="your-project-id"
GCP_LOCATION="us-central1"
NOTIFICATION_WEBHOOK_URL="https://hooks.slack.com/services/..."
2. メインプログラム (monitor_app.py)
day15_21.py
import os
import json
import logging
import httpx
from datetime import datetime
from dotenv import load_dotenv
from google import genai
from google.genai import types
# 環境変数の読み込みとロギング設定
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
PROJECT_ID = os.getenv("GCP_PROJECT_ID")
LOCATION = os.getenv("GCP_LOCATION", "us-central1")
WEBHOOK_URL = os.getenv("NOTIFICATION_WEBHOOK_URL")
# クライアントの初期化
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION)
# 外部通知関数
def send_notification(message: str):
"""外部サービス(Slack/Discord等)に通知を送信する"""
if not WEBHOOK_URL:
logger.warning("通知先URL未設定のためスキップします。")
return
try:
httpx.post(WEBHOOK_URL, json={"text": message}).raise_for_status()
logger.info("外部通知の送信に成功しました。")
except Exception as e:
logger.error(f"通知送信エラー: {e}")
# AIによるログ解析関数
def run_ai_audit(log_data: str):
"""AIによるログ解析を実行し、JSON形式で結果を返す"""
config = types.GenerateContentConfig(
response_mime_type="application/json",
system_instruction=(
"あなたはシニアSREエンジニアです。ログを解析し、"
"{'severity': 'HIGH/LOW', 'summary': '概要', 'action': '推奨アクション'} "
"という形式のJSONで回答してください。"
)
)
try:
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=f"以下のログを解析してください:\n{log_data}",
config=config
)
return json.loads(response.text)
except Exception as e:
logger.error(f"AI解析エラー: {e}"); return None
# メイン関数
def main():
dummy_logs = "2026-05-19 10:05:01 ERROR Database connection timeout after 30s."
audit_result = run_ai_audit(dummy_logs)
if audit_result:
notification_text = (
f"🚨 *AIインフラ監視レポート*\n"
f"【重要度】: {audit_result.get('severity')}\n"
f"【概要】: {audit_result.get('summary')}\n"
f"【対応】: {audit_result.get('action')}"
)
print(f"\n--- 解析結果 ---\n{notification_text}")
send_notification(notification_text)
if __name__ == "__main__":
main()