1. はじめに
概要
この投稿では、Google Agent Development Kit(ADK)と FastAPI を使用して Gemini エージェントを構築します。デプロイする前に、Cloud Run サービス ID と同じサービス アカウントを使用してローカルでテストするように、アプリケーションのデフォルト認証情報(ADC)を構成します。
Google スプレッドシートと通信するには、スプレッドシートにアクセスするための適切なスコープを持つ OAuth アクセス トークンが必要です。このアクセス トークンをローカルで実行する場合と、ADC を使用して Cloud Run で実行する場合に取得する方法は次のとおりです。
- ローカル: ADC は、
gcloud auth application-defaultコマンドで生成された認証情報を検出します。詳しくは、こちらをご覧ください。 - Cloud Run の場合: ADC は Metadata Server を使用して認証情報を取得します。詳しくは、こちらをご覧ください。
用語に関する注釈:
「ID の引き受け」または「同じ権限の引き受け」という用語の方がなじみ深いかもしれません。Google Cloud でサービス アカウントの権限を借用すると、認証されたプリンシパルは、そのサービス アカウントが許可されているすべてのものにアクセスできます。サービス アカウントの権限を借用できるのは、適切な権限を持つ認証済みのプリンシパルのみです。詳細については、https://docs.cloud.google.com/iam/docs/service-account-overview#impersonation をご覧ください。
学習内容
- ローカル環境でアプリケーションのデフォルト認証情報(ADC)を構成する方法
- Google スプレッドシートの読み取りと書き込みが可能な ADK エージェントを作成する方法
- Cloud Run にエージェントをデプロイする方法
2. 設定と要件
前提条件
- Cloud コンソールにログインしていること。
- Cloud Run サービスをデプロイ済みである。たとえば、Cloud Run サービスのデプロイに沿って作業を開始できます。
環境変数の設定
この Codelab 全体で使用する環境変数を設定できます。
シート ID は、共有リンクをコピーしたときに Google スプレッドシートの URL で確認できます(例: https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit?usp=sharing)。
PROJECT_ID=<YOUR-PROJECT-ID>
REGION=<YOUR_REGION>
SPREADSHEET_ID=<YOUR_SPREADSHEET_ID>
SA_NAME=sheet-agent-sa
SERVICE_ACCOUNT_EMAIL=$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com
必要な Google Cloud APIs を有効にする
gcloud services enable \
sheets.googleapis.com \
aiplatform.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com \
run.googleapis.com \
logging.googleapis.com \
--project=$PROJECT_ID
サービス アカウントを作成する
まず、次のコマンドを使用してサービス アカウントを作成します。
gcloud iam service-accounts create $SA_NAME \
--description="Service account for spreadsheet agent codelab" \
--display-name="Spreadsheet Agent Service Account" \
--project=$PROJECT_ID
次に、サービス アカウントに Vertex AI ユーザーロールを付与します(Vertex AI の Gemini モデルに必要)。
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
--role="roles/aiplatform.user"
gcloud ID にサービス アカウントの権限を借用する権限を付与します(ローカル開発に必要)。gcloud auth list を実行すると、gcloud ID を確認できます。
USER_EMAIL=$(gcloud config get-value account)
gcloud iam service-accounts add-iam-policy-binding $SERVICE_ACCOUNT_EMAIL \
--member="user:$USER_EMAIL" \
--role="roles/iam.serviceAccountTokenCreator" \
--project=$PROJECT_ID
- ブラウザで Google スプレッドシートを開きます。
- [共有] ボタンをクリックします。
- サービス アカウントのメールアドレス $SERVICE_ACCOUNT_EMAIL を貼り付け、編集者のアクセス権を付与します。
3. アプリを作成する
まず、ソースコードのディレクトリを作成し、そのディレクトリに移動します。
mkdir local-adk-sheets-codelab && cd $_
次に、次の内容の main.py ファイルを作成します。
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from google.auth import default
from googleapiclient.discovery import build
from google.adk.agents.llm_agent import Agent
from google.adk.runners import InMemoryRunner
# 1. Environment and Global Google Sheets Client Setup (ADC)
SPREADSHEET_ID = os.environ.get("SPREADSHEET_ID")
if not SPREADSHEET_ID:
raise ValueError("SPREADSHEET_ID environment variable is missing. Please set it before running.")
credentials, _ = default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
sheets_api = build('sheets', 'v4', credentials=credentials).spreadsheets()
# 2. Tools
def read_spreadsheet(range_name: str) -> dict:
"""Reads values from the Google Spreadsheet for a given range.
Args:
range_name: The A1 notation or R1C1 notation of the range to retrieve, e.g., 'Sheet1!A1:D10'.
"""
return sheets_api.values().get(spreadsheetId=SPREADSHEET_ID, range=range_name).execute()
def update_spreadsheet(range_name: str, values: list[list[str]]) -> dict:
"""Updates the Google Spreadsheet range with the specified grid of values.
Args:
range_name: The A1 notation or R1C1 notation of the range to update, e.g., 'Sheet1!C2'.
values: A list of lists of strings representing the grid of values to write.
"""
return sheets_api.values().update(
spreadsheetId=SPREADSHEET_ID,
range=range_name,
valueInputOption="USER_ENTERED",
body={"values": values}
).execute()
# 3. Agent Definition
MODEL_NAME = os.environ.get("GEMINI_MODEL", "gemini-3.1-flash-lite")
root_agent = Agent(
name="spreadsheet_agent",
model=MODEL_NAME,
instruction="""You are a helpful spreadsheet assistant.
You can read and write to the user's Google Spreadsheet using the tools provided.
Always use the appropriate tools when the user asks you to read or update a spreadsheet.
When updating a range, make sure the values parameter is a list of lists (e.g. [[value]]).
Be concise and helpful in your responses.""",
description="An agent that can read and write to a specific Google Spreadsheet.",
tools=[read_spreadsheet, update_spreadsheet]
)
# 4. FastAPI Application Setup
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
try:
async with InMemoryRunner(app_name="sheets_agent_app", agent=root_agent) as runner:
events = await runner.run_debug(request.prompt, quiet=True)
# Extract the final response text
texts = [
"".join(p.text for p in e.content.parts if p.text)
for e in reversed(events) if e.content and e.content.parts
]
return {"response": next((t for t in texts if t), "No response from agent.")}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
次に、次の内容の requirements.txt ファイルを作成します。
fastapi>=0.100.0
uvicorn>=0.22.0
google-adk>=1.27.1
google-auth
google-api-python-client
4. サービスをローカルでテストする
gcloud auth application-default login --impersonate-service-account=$SERVICE_ACCOUNT_EMAIL
GOOGLE_GENAI_USE_VERTEXAI=1 GOOGLE_CLOUD_PROJECT=$PROJECT_ID SPREADSHEET_ID=$SPREADSHEET_ID uvicorn main:app --host 0.0.0.0 --port 8080
別のターミナルからエージェントをテストします。
curl -X POST http://localhost:8080/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Update spreadsheet '$SPREADSHEET_ID' at range Sheet1!A1 with the value hello world"}'
サーバーは {"response":"The spreadsheet at Sheet1!A1 has been updated with the value \"hello world\"."} を返す必要があります。
5. Cloud Run にデプロイする
サービス アカウントにスプレッドシートにアクセスするための適切な権限があることがわかったので、サービス アカウントをサービス ID として使用して Cloud Run にデプロイします。
gcloud run deploy local-adk-sheets-codelab \
--source . \
--region=$REGION \
--set-env-vars GOOGLE_GENAI_USE_VERTEXAI=1,GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GOOGLE_CLOUD_LOCATION=global,SPREADSHEET_ID=$SPREADSHEET_ID \
--service-account $SERVICE_ACCOUNT_EMAIL \
--no-allow-unauthenticated \
--project=$PROJECT_ID
デプロイが完了したら、Cloud Run サービスにプロンプトを送信します。
# Retrieve the Service URL
SERVICE_URL=$(gcloud run services describe local-adk-sheets-codelab --region $REGION --format 'value(status.url)')
curl -X POST $SERVICE_URL/chat \
-H "Authorization: bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json" \
-d '{"prompt": "Update spreadsheet '$SPREADSHEET_ID' at range Sheet1!A1 with the value hello world"}'
{"response":"OK. I've updated cell A1 in Sheet1 with \"hello world\"."} のレスポンスが返されます。
Google スプレッドシートを開きます。最初のセルに「hello world」という値が表示されます。
6. 完了
以上で、この Codelab は完了です。
次のステップ
エージェントの機能を拡張するには、次のドキュメントをご覧ください。
- Google Agent Development Kit(ADK)を使用して、高度なエージェント ワークフローを試す
- Cloud Run で AI ソリューションを構築するためのベスト プラクティスをご覧ください。
- Cloud Run から Google Cloud APIs に対する認証を安全に行う方法を理解する。
学習した内容
- ローカル環境でアプリケーションのデフォルト認証情報(ADC)を構成する方法
- Google スプレッドシートの読み取りと書き込みが可能な ADK エージェントを作成する方法
- Cloud Run にエージェントをデプロイする方法
7. クリーンアップ
誤って課金されないように(たとえば、この Cloud Run 関数が 無料枠の Cloud Run 呼び出しの月間割り当てよりも多く呼び出された場合など)、Cloud Run サービスを削除するか、プロジェクトを削除します。
Cloud Run サービスを削除するには、Cloud Console の https://console.cloud.google.com/run/ に移動し、この Codelab で作成したサービス local-adk-sheets-codelab を削除します。
プロジェクト全体を削除する場合は、https://console.cloud.google.com/cloud-resource-manager に移動し、ステップ 2 で作成したプロジェクトを選択して、[削除] を選択します。プロジェクトを削除した場合は、Cloud SDK でプロジェクトを変更する必要があります。gcloud projects list を実行すると、使用可能なすべてのプロジェクトのリストを表示できます。