1. מבוא
סקירה כללית
בפוסט הזה נסביר איך ליצור סוכן Gemini באמצעות ערכה לפיתוח סוכנים (ADK) של Google ו-FastAPI. לפני הפריסה, תגדירו Application Default Credentials (ADC) כדי לבצע בדיקה מקומית באמצעות אותו חשבון שירות שמשמש כזהות של שירות Cloud Run.
כדי שהאפליקציה תוכל לתקשר עם Google Sheets, היא צריכה טוקן גישה של OAuth עם היקף ההרשאות המתאים לגישה לגיליון האלקטרוני. תלמדו איך לקבל את אסימון הגישה הזה כשמריצים באופן מקומי וב-Cloud Run עם ADC:
- באופן מקומי: ADC מוצא את פרטי הכניסה שנוצרו באמצעות הפקודה
gcloud auth application-default. מידע נוסף - ב-Cloud Run: ADC משתמש בשרת המטא-נתונים כדי לקבל פרטי כניסה. מידע נוסף זמין כאן.
הערה לגבי המינוח:
יכול להיות שאתם מכירים יותר את המונחים 'התחזות לזהות' או 'קבלת אותן הרשאות'. ב-Google Cloud, התחזות לחשבון שירות מאפשרת לישות מאומתת לגשת לכל מה שחשבון השירות יכול לגשת אליו. רק חשבונות משתמשים מאומתים עם ההרשאות המתאימות יכולים להתחזות לחשבונות שירות. מידע נוסף זמין בכתובת https://docs.cloud.google.com/iam/docs/service-account-overview#impersonation
מה תלמדו
- איך מגדירים Application Default Credentials (ADC) בסביבה המקומית
- איך ליצור סוכן ADK שיכול לקרוא ולכתוב בגיליון אלקטרוני ב-Google Sheets
- איך פורסים את הסוכן ב-Cloud Run
2. הגדרה ודרישות
דרישות מוקדמות
- אתם מחוברים ל-Cloud Console.
- כבר פרסתם שירות Cloud Run. לדוגמה, אפשר לפעול לפי השלבים לפריסת שירות Cloud Run כדי להתחיל.
הגדרה של משתני סביבה
אתם יכולים להגדיר משתני סביבה שישמשו אתכם לאורך כל ה-codelab הזה.
אפשר למצוא את מזהה הגיליון בכתובת ה-URL של גיליון Google כשמעתיקים את קישור השיתוף, למשל: 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 API הנדרשים
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' לחשבון השירות (נדרש למודלים של Gemini ב-Vertex AI)
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
--role="roles/aiplatform.user"
נותנים לזהות ב-gcloud הרשאה להתחזות לחשבון השירות (נדרש לפיתוח מקומי). כדי לראות את הזהויות שלכם ב-gcloud, מריצים את הפקודה gcloud auth list
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. יצירת האפליקציה
קודם יוצרים ספרייה לקוד המקור ועוברים לספרייה הזו באמצעות הפקודה cd.
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
עכשיו אתם יודעים שלחשבון השירות יש את ההרשאות המתאימות לגישה לגיליון האלקטרוני, ולכן תפרסו אותו ב-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 Sheets. הערך 'hello world' יופיע בתא הראשון.
6. מעולה!
כל הכבוד, סיימתם את ה-Codelab!
מה השלב הבא?
כדי להרחיב את היכולות של הסוכן, מומלץ לעיין במסמכים הבאים:
- אפשר לבחון תהליכי עבודה מתקדמים של סוכנים באמצעות הערכה לפיתוח סוכנים (ADK) של Google
- שיטות מומלצות נוספות ליצירת פתרונות מבוססי-AI ב-Cloud Run
- איך מבצעים אימות לממשקי Google Cloud API מ-Cloud Run בצורה מאובטחת
מה נכלל
- איך מגדירים Application Default Credentials (ADC) בסביבה המקומית
- איך ליצור סוכן ADK שיכול לקרוא ולכתוב בגיליון אלקטרוני ב-Google Sheets
- איך פורסים את הסוכן ב-Cloud Run
7. הסרת המשאבים
כדי להימנע מחיובים לא מכוונים (לדוגמה, אם הפונקציה הזו של Cloud Run מופעלת בטעות יותר פעמים מהקצאת ההפעלות החודשית של Cloud Run בחבילה ללא תשלום), אפשר למחוק את שירות Cloud Run או למחוק את הפרויקט.
כדי למחוק שירות Cloud Run, עוברים אל Cloud Run במסוף Cloud בכתובת https://console.cloud.google.com/run/ ומוחקים את השירות local-adk-sheets-codelab שיצרתם ב-codelab הזה.
אם אתם רוצים למחוק את הפרויקט כולו, אתם יכולים להיכנס לכתובת https://console.cloud.google.com/cloud-resource-manager, לבחור את הפרויקט שיצרתם בשלב 2 וללחוץ על 'מחיקה'. אם תמחקו את הפרויקט, תצטרכו לשנות את הפרויקטים ב-Cloud SDK. כדי לראות את רשימת כל הפרויקטים הזמינים, מריצים את הפקודה gcloud projects list.