Vertex AI Agent Builder 入門ガイド — ノーコードでGeminiエージェントを構築
Vertex AI Agent Builder は、Gemini をベースとしたカスタムエージェントをノーコードで構築・デプロイできるツールです。このガイドでは、初期設定からプロダクション運用までのステップを解説します。
Agent Builder の概要
主な機能
- ノーコード UI: コードを書かずにエージェント構築
- マルチデータソース対応: Cloud Storage、BigQuery、ウェブサイトのデータを連携
- カスタムツール: REST API やサーバーレス関数を統合
- 会話履歴管理: 長期にわたる会話コンテキストを自動管理
- 組み込みテスト: Playground でのリアルタイムテスト
- API デプロイ: 標準 REST API として提供
Vertex AI Agent Builder は Google Cloud の管理画面から直接アクセスでき、特別なセットアップは不要です。
セットアップと初期構成
前提条件
# Google Cloud プロジェクトのセットアップ
gcloud projects create my-agent-project
gcloud config set project my-agent-project
# 必要な API の有効化
gcloud services enable \
aiplatform.googleapis.com \
cloudfunctions.googleapis.com \
run.googleapis.com \
storage-api.googleapis.com \
bigquery.googleapis.comエージェントの作成
- Google Cloud Console にアクセス
- Vertex AI → Agent Builder を選択
- エージェントを作成 をクリック
- 以下の情報を入力:
- エージェント名: 例)
customer-support-agent - 説明: エージェントの目的を記載
- モデル:
Gemini 2.5 ProまたはGemini 3 Proを選択 - リージョン:
asia-northeast1(日本) を推奨
- エージェント名: 例)
エージェント命令(System Prompt)の設定
基本的なプロンプト設定
Console UI で以下のセクションに入力:
エージェントの役割:
あなたはカスタマーサポートエージェントです。ユーザーの質問に対して、
ナレッジベースに基づいた回答を提供します。
行動ガイドライン:
1. まず、ユーザーの意図を理解してください
2. 関連するドキュメントを検索してください
3. 信頼できる情報のみを提供してください
4. 回答不可の場合は、人間のエージェントへのエスカレーションを提案してください
言語: 日本語
トーン: 丁寧かつ親切
Python による動的プロンプト設定
from google.cloud import aiplatform
from google.protobuf.struct_pb2 import Struct, Value
def create_agent_with_custom_prompt(project_id, region, agent_name, prompt_text):
"""カスタムプロンプト付きでエージェントを作成"""
client = aiplatform.gapic.v1.AgentsClient(
client_options={"api_endpoint": f"{region}-aiplatform.googleapis.com"}
)
location = client.common_location_path(project_id, region)
# エージェント設定
agent = {
"display_name": agent_name,
"description": "Custom Gemini Agent",
"system_instruction": {
"parts": [{"text": prompt_text}]
},
"model": "gemini-2.5-pro"
}
request = {
"parent": location,
"agent": agent
}
response = client.create_agent(request)
return response
# 使用例
prompt = """あなたはテクニカルサポートエージェントです。
ユーザーの技術的な問題を診断し、段階的な解決策を提供します。"""
agent = create_agent_with_custom_prompt(
project_id="my-project",
region="asia-northeast1",
agent_name="technical-support",
prompt_text=prompt
)データストアの連携
Cloud Storage との連携
-
ナレッジベース作成:
- Agent Builder コンソール → データストア
- データストアを作成 → クラウドストレージ
- GCS バケットパスを指定(例:
gs://my-knowledge-base/docs)
-
ドキュメント準備:
# ドキュメントをアップロード
gsutil cp -r ./documents/* gs://my-knowledge-base/docs/- 検索設定:
- 検索タイプ: ハイブリッド検索(キーワード + セマンティック)
- チャンクサイズ: 1000 トークン
- オーバーラップ: 200 トークン
BigQuery との連携
-- BigQuery テーブルの例
CREATE TABLE `my-project.agent_data.products` (
product_id STRING,
product_name STRING,
description STRING,
price FLOAT64,
stock_quantity INT64,
created_at TIMESTAMP
);
-- サンプルデータ挿入
INSERT INTO `my-project.agent_data.products` VALUES
('PROD001', 'Python 入門書', 'Python 初心者向けの教科書', 2800.00, 150, CURRENT_TIMESTAMP()),
('PROD002', 'API 設計ガイド', 'REST API 設計のベストプラクティス', 3500.00, 80, CURRENT_TIMESTAMP());Agent Builder で BigQuery データソースを指定:
- パス:
projects/my-project/datasets/agent_data/tables/products - クエリ タイプ: 自動生成(LLM がクエリを動的生成)
Web サイトのクロール
-
Data Store 設定:
- ウェブサイト を選択
- クロール対象 URL を入力(例:
https://docs.example.com) - クロール深度: 3 レベル
-
更新スケジュール設定:
- 自動更新: 毎日午前 2 時
著作権保有のコンテンツをクロールする際は、robots.txt とサイトの利用規約を確認してください。
カスタムツール(関数)の定義
Cloud Functions との統合
# Cloud Functions: product_lookup.py
import functions_framework
import json
from google.cloud import bigquery
client = bigquery.Client()
@functions_framework.http
def lookup_product(request):
"""商品情報を検索"""
request_json = request.get_json()
product_id = request_json.get('product_id')
if not product_id:
return json.dumps({
"status": "error",
"message": "product_id is required"
}), 400
# BigQuery クエリ
query = f"""
SELECT
product_id,
product_name,
description,
price,
stock_quantity
FROM `my-project.agent_data.products`
WHERE product_id = '{product_id}'
LIMIT 1
"""
results = list(client.query(query).result())
if results:
product = results[0]
return json.dumps({
"status": "success",
"product": {
"id": product['product_id'],
"name": product['product_name'],
"description": product['description'],
"price": float(product['price']),
"stock": int(product['stock_quantity'])
}
}), 200
else:
return json.dumps({
"status": "not_found",
"message": f"Product {product_id} not found"
}), 404
# デプロイ
# gcloud functions deploy lookup_product \
# --runtime python311 \
# --trigger-http \
# --allow-unauthenticatedツール定義(Agent Builder UI)
- ツールを追加 をクリック
- REST API を選択
- 以下の設定を入力:
{
"name": "product_lookup",
"description": "商品 ID から商品情報を取得する",
"endpoint": "https://REGION-my-project.cloudfunctions.net/lookup_product",
"method": "POST",
"parameters": [
{
"name": "product_id",
"type": "string",
"description": "商品ID(例:PROD001)",
"required": true
}
],
"response_schema": {
"type": "object",
"properties": {
"status": {"type": "string"},
"product": {
"type": "object",
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"price": {"type": "number"},
"stock": {"type": "integer"}
}
}
}
}
}Playground でのテスト
基本的なテスト
- Agent Builder UI の右側パネル「Playground」を開く
- テストメッセージを入力:
PROD001 の商品情報を教えてください - 送信 をクリック
- エージェントの応答を確認
テスト事例
質問: 3000円以下の商品を教えてください
期待動作:
- BigQuery にクエリ
- 条件に合う商品を検索
- 結果をテーブル形式で提示
質問: 在庫が 100 個以上ある商品はありますか?
期待動作:
- 複数の商品を検索
- 比較分析
- リスト形式で提示
Playground ではリアルタイムでエージェントの動作を確認できます。デプロイ前に十分なテストを行いましょう。
API エンドポイントへのデプロイ
手動デプロイ
- Agent Builder UI で デプロイ をクリック
- デプロイ方式を選択:
- API エンドポイント: REST API として公開
- チャットアプリケーション: Vertex AI チャットウィジェット
- Slack: Slack ワークスペースに統合
Cloud Run へのデプロイ
# エージェント ID を取得
AGENT_ID="projects/my-project/locations/asia-northeast1/agents/abc123"
# Cloud Run でエージェントをデプロイ
gcloud run deploy my-agent \
--image gcr.io/cloud-ai-solutions/agent-runtime:latest \
--environment-variables AGENT_ID=$AGENT_ID \
--region asia-northeast1 \
--allow-unauthenticatedPython から API を呼び出し
REST API クライアント
import requests
import json
class AgentAPIClient:
"""Vertex AI Agent API クライアント"""
def __init__(self, endpoint_url, api_key):
self.endpoint = endpoint_url
self.api_key = api_key
def send_message(self, user_message, session_id=None):
"""エージェントにメッセージを送信"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"user_input": user_message,
"session_id": session_id or "default-session"
}
response = requests.post(
f"{self.endpoint}/chat",
headers=headers,
json=payload
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API Error: {response.status_code}")
def get_session_history(self, session_id):
"""セッション履歴を取得"""
headers = {
"Authorization": f"Bearer {self.api_key}"
}
response = requests.get(
f"{self.endpoint}/sessions/{session_id}/history",
headers=headers
)
return response.json() if response.status_code == 200 else []
# 使用例
client = AgentAPIClient(
endpoint_url="https://REGION-my-project.run.app",
api_key="your-api-key"
)
# メッセージ送信
response = client.send_message(
user_message="PROD001 と PROD002 の価格を比較してください",
session_id="user-123"
)
print("エージェント応答:", response.get("response"))
print("使用ツール:", response.get("tools_used", []))
# セッション履歴の確認
history = client.get_session_history("user-123")
for msg in history:
print(f"{msg['role']}: {msg['content']}")モニタリングと分析
Cloud Logging での監視
# ログの確認
gcloud logging read \
"resource.type=cloud_run_revision AND \
resource.labels.service_name=my-agent" \
--limit 50
# フィルタリング例:エラーのみ表示
gcloud logging read \
"severity=ERROR AND resource.type=cloud_run_revision" \
--limit 20Python でログ分析
from google.cloud import logging as cloud_logging
from datetime import datetime, timedelta
def analyze_agent_usage(project_id, hours=24):
"""エージェント使用統計を分析"""
logging_client = cloud_logging.Client(project=project_id)
logger = logging_client.logger("agent-analytics")
# 過去 24 時間のログを取得
start_time = datetime.utcnow() - timedelta(hours=hours)
filter_str = f"""
timestamp >= "{start_time.isoformat()}Z" AND
resource.type="cloud_run_revision" AND
jsonPayload.agent_id="{project_id}"
"""
entries = logging_client.list_entries(filter_=filter_str)
stats = {
"total_messages": 0,
"successful_queries": 0,
"failed_queries": 0,
"average_response_time": 0,
"tools_used": {}
}
response_times = []
for entry in entries:
payload = entry.payload
stats["total_messages"] += 1
if payload.get("status") == "success":
stats["successful_queries"] += 1
else:
stats["failed_queries"] += 1
# 応答時間を記録
if "response_time_ms" in payload:
response_times.append(payload["response_time_ms"])
# 使用ツールの集計
for tool in payload.get("tools_used", []):
stats["tools_used"][tool] = stats["tools_used"].get(tool, 0) + 1
if response_times:
stats["average_response_time"] = sum(response_times) / len(response_times)
return stats
# 使用例
usage = analyze_agent_usage("my-project")
print(f"総メッセージ数: {usage['total_messages']}")
print(f"成功: {usage['successful_queries']}, 失敗: {usage['failed_queries']}")
print(f"平均応答時間: {usage['average_response_time']:.2f}ms")
print(f"使用ツール: {usage['tools_used']}")ベストプラクティス
1. 段階的な構築
Phase 1: 最小限のセットアップ
- シンプルなシステムプロンプト
- 1つのデータソース
- 基本的なテスト
Phase 2: 機能拡張
- 複数のデータソース
- カスタムツール追加
- より詳細なテスト
Phase 3: プロダクション化
- 監視・ログ設定
- パフォーマンス最適化
- セキュリティ強化
2. セキュリティ設定
# サービスアカウント権限の最小化
gcloud iam roles create agent-runtime-role \
--permissions=bigquery.dataEditor,storage.objectViewer,run.invoker
# Firestore/Datastore での会話履歴の暗号化
gcloud firestore databases create \
--database-type=firestore-native \
--cmek-config=projects/my-project/locations/global/keyRings/my-keyring/cryptoKeys/my-key本番環境では必ず認証・認可を実装し、データベースアクセスには適切な権限制御を設定してください。
全体を振り返って
Vertex AI Agent Builder により、以下のようなエージェント構築が可能です:
- カスタマーサポート: FAQベース の自動応答
- 営業支援: CRM データとの連携
- テクニカルサポート: ナレッジベース検索
- データ分析: BigQuery データの自動分析
ノーコード UI により、開発効率を大幅に向上させながら、エンタープライズグレードの機能を実現できます。