Contents
- 1 1️⃣ 前提条件と準備
- 2 2️⃣ GCP プロジェクトの作成
- 3 3️⃣ Vertex AI と Gemini API の有効化
- 4 4️⃣ 課金設定・無料枠の確認
- 5 5️⃣ IAM ロールとサービスアカウントの最小権限構成
- 6 6️⃣ データセット作成・Cloud Storage へのアップロード
- 7 7️⃣ Gemini API キーを Secret Manager に保存
- 8 8️⃣ モデルエンドポイントの作成とデプロイ
- 9 9️⃣ モニタリング・ロギング・コスト管理
- 10 🔟 CI/CD(Cloud Build + Terraform)
- 11 1️⃣1️⃣ よくある課題と対処法
- 12 1️⃣2️⃣ まとめ
- 13 参考文献
1️⃣ 前提条件と準備
| 必要なもの | 内容 |
|---|---|
| Google アカウント | GCP の無料トライアルに登録できる個人または企業アカウント |
| ブラウザ | Chrome / Edge 推奨(Google Cloud Console の UI が最適化) |
| ローカル環境 | gcloud CLI、python >=3.9、node >=18、terraform >=1.5 がインストール済み |
| 権限 | プロジェクト作成者(Owner)または Billing Administrator の権限が必要 |
※ UI は頻繁に更新されます。最新のナビゲーションは公式コンソールヘルプ[^1]をご確認ください。
2️⃣ GCP プロジェクトの作成
手順概要
| ステップ | 操作 |
|---|---|
| ① | https://console.cloud.google.com/ にアクセスし、Google アカウントでサインイン |
| ② | 左上メニュー(ハンバーガーアイコン) → 「プロジェクト」 を選択 |
| ③ | 「新しいプロジェクト」 ボタンをクリック |
| ④ | プロジェクト名、プロジェクト ID、リージョン(例: us-central1)を入力し 作成 |
| ⑤ | 作成直後に 課金アカウント を紐付ける画面が表示されます。自動的に $300 のトライアルクレジットが付与されます[^2] |
ポイント
- UI が 2024/09 に刷新されたことを踏まえて、左サイドバーでは「リソース管理」→「プロジェクト」の順に辿りますが、将来的にメニュー項目名が変わる可能性があります。公式ドキュメントで最新構成を随時確認してください。
3️⃣ Vertex AI と Gemini API の有効化
|
1 2 3 4 5 6 |
# 必要なサービスを一括有効化 gcloud services enable \ aiplatform.googleapis.com \ cloudresourcemanager.googleapis.com \ secretmanager.googleapis.com |
| API | 用途 |
|---|---|
aiplatform.googleapis.com |
Vertex AI の全機能(データセット、トレーニング、エンドポイント) |
gemini.googleapis.com (※ Gemini は aiplatform.googleapis.com に統合) |
Generative AI モデル呼び出し |
参考:Google が公開している「Vertex AI の無料枠とトライアル」ページに、Gemini 1.5‑pro の月間 30 M トークンまでが無償で利用可能と記載されています[^3]。
4️⃣ 課金設定・無料枠の確認
| 項目 | 内容 | 出典 |
|---|---|---|
| トライアルクレジット | 新規アカウントに $300(90 日間)を自動付与 | [^2] |
| Vertex AI 無料枠 | トレーニング・デプロイ 1000 時間まで無料 | Google Cloud Billing Docs |
| Gemini API 無料トークン | 月間 30 M トークン(約 300,000 リクエスト)まで無償 | [^3] |
予算とアラートの設定例
|
1 2 3 4 5 6 7 8 |
# 月額 $20 の予算を作成し、超過時にメール通知 gcloud beta billing budgets create \ --billing-account=YOUR_BILLING_ACCOUNT_ID \ --display-name="GenAI Monthly Budget" \ --budget-amount=20 \ --threshold-rule-percentage=0.5,1.0 \ --all-updates-rule-email-recipients=user@example.com |
5️⃣ IAM ロールとサービスアカウントの最小権限構成
5‑1. サービスアカウント作成
|
1 2 3 |
gcloud iam service-accounts create genai-sa \ --display-name="Generative AI Service Account" |
5‑2. 必要ロールの付与(最小権限)
| ロール | 権限概要 |
|---|---|
roles/aiplatform.user |
Vertex AI のモデル作成・デプロイ・エンドポイント操作 |
roles/secretmanager.secretAccessor |
Secret Manager からシークレット取得 |
roles/storage.objectViewer (オプション) |
データセット格納バケットの読み取り |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
PROJECT_ID=$(gcloud config get-value project) # aiplatform.user ロール付与 gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:genai-sa@$PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" # Secret Manager アクセス権追加 gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceMember:serviceAccount:genai-sa@$PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/secretmanager.secretAccessor" |
ベストプラクティス:Google が推奨する「最小権限の原則」[^4] に従い、不要なロールは付与しない。
6️⃣ データセット作成・Cloud Storage へのアップロード
6‑1. ファイルフォーマット例
CSV(ヘッダー必須)
|
1 2 3 4 |
prompt,completion "東京の天気は?","晴れです。" "Python のリストを逆順にする方法は?","list.reverse() を使用します。" |
JSONL(1 行 1 オブジェクト)
|
1 2 3 |
{"prompt":"東京の天気は?","completion":"晴れです。"} {"prompt":"Python のリストを逆順にする方法は?","completion":"list.reverse() を使用します。"} |
6‑2. バケット作成とデータアップロード
|
1 2 3 4 5 6 |
# バケット作成(リージョンはプロジェクトと同じ us-central1 推奨) gsutil mb -l us-central1 gs://my-genai-dataset/ # データファイルをアップロード gsutil cp dataset.csv gs://my-genai-dataset/ |
ポイント:Vertex AI のデータセットインポートは、対象バケットの
storage.objectViewer権限が必要です。サービスアカウントに付与済みか確認してください。
7️⃣ Gemini API キーを Secret Manager に保存
7‑1. API キー取得手順(コンソール)
- コンソール左メニュー → 「API とサービス」 → 「認証情報」
- 「認証情報を作成」→ 「API キー」 を選択し、表示されたキーをコピー
注意:生成したキーは一度だけ表示されます。必ず安全な場所に保存してください。
7‑2. Secret Manager にシークレットとして格納
|
1 2 3 4 5 6 7 8 9 |
printf "YOUR_GEMINI_API_KEY" | \ gcloud secrets create gemini-api-key \ --replication-policy="automatic" # サービスアカウントへアクセス権付与 gcloud secrets add-iam-policy-binding gemini-api-key \ --member="serviceAccount:genai-sa@$PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/secretmanager.secretAccessor" |
7‑3. Python で取得するユーティリティ
|
1 2 3 4 5 6 7 8 |
from google.cloud import secretmanager def get_gemini_key(project_id: str) -> str: client = secretmanager.SecretManagerServiceClient() name = f"projects/{project_id}/secrets/gemini-api-key/versions/latest" response = client.access_secret_version(request={"name": name}) return response.payload.data.decode("UTF-8") |
8️⃣ モデルエンドポイントの作成とデプロイ
8‑1. Python クライアントで Gemini にプロンプト送信
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import os from google.cloud import aiplatform PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") LOCATION = "us-central1" def init_aiplatform(): client_options = {"api_endpoint": f"{LOCATION}-aiplatform.googleapis.com"} aiplatform.init(project=PROJECT_ID, location=LOCATION, client_options=client_options) def generate_text(prompt: str) -> str: model_name = "gemini-1.5-pro" model = aiplatform.Model(model_name=model_name) response = model.predict(instances=[{"prompt": prompt}]) return response.predictions[0]["completion"] if __name__ == "__main__": os.environ["GEMINI_API_KEY"] = get_gemini_key(PROJECT_ID) # Secret Manager から取得 init_aiplatform() print(generate_text("東京のおすすめ観光スポットは?")) |
8‑2. エンドポイント作成(CLI)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# 1. エンドポイント作成 gcloud ai endpoints create \ --region=us-central1 \ --display-name="gemini-endpoint" # 2. モデルのアップロード(公式コンテナイメージ使用) MODEL_ID=$(gcloud ai models upload \ --region=us-central1 \ --container-image-uri=gcr.io/cloud-aiplatform/prediction/gemini:latest \ --display-name="gemini-model" \ --format="value(name)") # 3. デプロイ(Auto‑Scaling 設定) gcloud ai endpoints deploy-model $(gcloud ai endpoints list --region=us-central1 --format="value(name)" --filter="display_name=gemini-endpoint") \ --model=$MODEL_ID \ --display-name="gemini-deployment" \ --machine-type=n1-standard-4 \ --min-replica-count=1 \ --max-replica-count=5 \ --traffic-split=0=100 |
8‑3. Node.js バージョン(参考実装)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const {EndpointServiceClient} = require('@google-cloud/aiplatform').v1; const {SecretManagerServiceClient} = require('@google-cloud/secret-manager'); async function getGeminiKey() { const client = new SecretManagerServiceClient(); const [version] = await client.accessSecretVersion({ name: `projects/${process.env.GCLOUD_PROJECT}/secrets/gemini-api-key/versions/latest`, }); return version.payload.data.toString('utf8'); } async function generateText(prompt) { const endpointClient = new EndpointServiceClient(); const endpoint = `projects/${process.env.GCLOUD_PROJECT}/locations/us-central1/endpoints/<ENDPOINT_ID>`; const request = { endpoint, instances: [{prompt}], parameters: {}, }; const [response] = await endpointClient.predict(request); console.log(response.predictions[0].completion); } (async () => { process.env.GEMINI_API_KEY = await getGeminiKey(); await generateText('Python のリスト内包表記の例は?'); })(); |
Tip:
<ENDPOINT_ID>はgcloud ai endpoints listコマンドで取得できます。
9️⃣ モニタリング・ロギング・コスト管理
9‑1. ログの確認
- Logging ビューア:コンソール → 「ログビューア」 → フィルタ
resource.type="aiplatform_endpoint" - 主なフィールド:
prediction.input,prediction.output,response.status
9‑2. メトリクスとアラート
| メトリクス | 推奨閾値例 |
|---|---|
aiplatform.googleapis.com/endpoint/prediction_latency |
平均 > 2 秒 → Slack 通知 |
aiplatform.googleapis.com/endpoint/prediction_error_count |
1 時間あたり > 5 件 → メール警告 |
アラート作成(CLI)
|
1 2 3 4 5 6 7 8 |
gcloud monitoring policies create \ --notification-channels=YOUR_SLACK_CHANNEL_ID \ --condition-display-name="High Prediction Latency" \ --condition-filter='metric.type="aiplatform.googleapis.com/endpoint/prediction_latency"' \ --condition-comparison=COMPARISON_GT \ --condition-threshold-value=2 \ --condition-duration=300s |
9‑3. コスト監視
- 予算アラートは上記 §4 の通り設定し、
$20を超えると Slack / Email に通知 - BigQuery Export(オプション)で課金レポートを分析し、トークン使用量と実際の請求額を突き合わせる
🔟 CI/CD(Cloud Build + Terraform)
10‑1. Terraform でインフラ定義(抜粋)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
terraform { required_version = ">= 1.5" required_providers { google = { source = "hashicorp/google", version = "~> 4.0" } } } provider "google" { project = var.project_id region = "us-central1" } resource "google_project_service" "aiplatform" { service = "aiplatform.googleapis.com" } resource "google_ai_endpoint" "gemini_endpoint" { display_name = "gemini-endpoint" location = "us-central1" } |
10‑2. Cloud Build のパイプライン
cloudbuild.yaml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
steps: # Terraform 初期化・適用 - name: 'hashicorp/terraform:1.5.7' entrypoint: '/bin/sh' args: - '-c' - | terraform init -input=false terraform apply -auto-approve -input=false # デプロイスクリプト(Python)実行 - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: 'bash' args: - '-c' - | pip install --quiet google-cloud-aiplatform python deploy_endpoint.py # エンドポイント作成・モデルデプロイ # バジェット/アラート設定(任意) - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: 'bash' args: - '-c' - | gcloud beta billing budgets create --billing-account=$BILLING_ACCOUNT_ID \ --display-name="GenAI Budget" --budget-amount=20 \ --threshold-rule-percentage=0.5,1.0 timeout: "1200s" |
deploy_endpoint.py(簡易例)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import os from google.cloud import aiplatform PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT") REGION = "us-central1" def main(): aiplatform.init(project=PROJECT, location=REGION) endpoint = aiplatform.Endpoint.create(display_name="gemini-endpoint") model = aiplatform.Model.upload( display_name="gemini-model", container_image_uri="gcr.io/cloud-aiplatform/prediction/gemini:latest" ) model.deploy(endpoint=endpoint, machine_type="n1-standard-4", min_replica_count=1, max_replica_count=5) print(f"Endpoint {endpoint.resource_name} deployed successfully.") if __name__ == "__main__": main() |
メリット:コードの変更だけでインフラとデプロイが自動的に再構成され、手作業ミスを防げます。
1️⃣1️⃣ よくある課題と対処法
| 症状 | 原因例 | 解決策 |
|---|---|---|
| 「予期せぬ課金が発生」 | Auto‑Scaling の max-replica-count が過大、もしくは無料トークン上限を超えている |
max-replica-count を 2–3 に抑えるか、budget alerts で即時停止(billing account disable) |
| 「モデルがデプロイできない」 | コンテナイメージのバージョン不一致(最新は gemini:latest が非推奨) |
Google の公式コンテナリストから現在サポートされているタグを確認[^5] |
| 「Secret Manager からキーが取得できない」 | サービスアカウントに secretAccessor ロール未付与、またはシークレットのレプリケーション設定が不適切 |
IAM バインディングを再度確認し、automatic レプリケーションで全リージョンからアクセス可能に |
| 「データセット取り込み時にバリデーションエラー」 | CSV のヘッダー名が prompt,completion 以外、または空行が混在 |
ファイルをローカルで csvlint / jq にて検証し、必ずヘッダーと UTF‑8 エンコーディングに統一 |
1️⃣2️⃣ まとめ
- プロジェクト作成 → サービス有効化 → 最小権限のサービスアカウント の順でセットアップすれば、数分で開発環境が整います。
- 無料枠 + $300 トライアルクレジット をフル活用すれば、実験段階のコストはほぼゼロです(ただしトークン上限と自動スケーリングには注意)。
- Secret Manager と IAM の最小権限 によって API キー漏洩リスクを低減し、予算アラート + Cloud Monitoring が運用の安全弁となります。
- CI/CD(Terraform + Cloud Build) を導入すれば、インフラ変更・モデル再デプロイがコードレビューと同様に管理でき、チーム開発に必須です。
これらを踏まえて、まずは無料クレジットで「my‑genai‑demo」プロジェクトを作成し、サンプルコード (generate_text) を実行してみてください。その後、独自データセットとカスタムモデルに置き換えるだけで、本格的な生成 AI アプリが完成します。
参考文献
[^1]: Google Cloud Console ヘルプ – 「ナビゲーション メニューの使用方法」 https://cloud.google.com/docs/overview/navigation
[^2]: 無料トライアルと $300 クレジットの詳細 – Google Cloud Free Tier https://cloud.google.com/free
[^3]: Gemini API の無料トークン情報 – 「Generative AI on Vertex AI」 https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini#pricing
[^4]: 最小権限の原則(Least Privilege) – Google Cloud Security Best Practices https://cloud.google.com/security/best-practices/least-privilege
[^5]: Vertex AI 用公式コンテナイメージ一覧 – https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers