כדי לאפשר לסוכנים שלכם לבצע אימות לכלים חיצוניים כמו מפות Google או ממשקי API של מזג האוויר, צריך להגדיר אימות יוצא באמצעות ספקי אימות של מפתחות API במנהל האימות של זהות הסוכן.
ספקי אימות של מפתחות API מנהלים בשבילכם את מפתחות ההצפנה. היכולת הזו מבטלת את הצורך להצפין מפתחות בקוד של הסוכן או לנהל אותם באופן ידני.
תהליך העבודה של מפתח API
ספקי אימות באמצעות מפתח API משתמשים בזהות של הסוכן ולא דורשים הסכמה מהמשתמש. Google נוקטת אמצעים כדי לעזור להגן על מפתח ה-API במהלך האחסון. כשמשתמשים בערכה לפיתוח סוכנים (ADK), היא מאחזרת באופן אוטומטי את מפתח ה-API ומוסיפה אותו לכותרות של קריאות הכלים.
לפני שמתחילים
- מוודאים שבחרתם את שיטת האימות הנכונה.
מפעילים את Agent Identity API.
תפקידים שנדרשים להפעלת ממשקי API
כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של שימוש בשירות' (
roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאהserviceusage.services.enable. איך מקצים תפקידיםמקבלים מפתח API משירות הצד השלישי שאליו רוצים להתחבר.
מוודאים שיש לכם את התפקידים הנדרשים כדי להשלים את המשימה הזו.
התפקידים הנדרשים
כדי לקבל את ההרשאות שדרושות ליצירה ולשימוש בספק אימות של מפתח API, צריך לבקש מהאדמין להקצות לכם בפרויקט את תפקידי ה-IAM הבאים:
-
כדי ליצור ספקי אימות:
- אדמין של זהויות סוכנים (
roles/agentidentity.admin) - עורך זהויות של סוכנים (
roles/agentidentity.editor)
- אדמין של זהויות סוכנים (
-
כדי להשתמש בספקי אימות:
- משתמש בזהות של סוכן (
roles/agentidentity.user) - משתמש Vertex AI (
roles/aiplatform.user) - צרכן שימוש בשירות (
roles/serviceusage.serviceUsageConsumer)
- משתמש בזהות של סוכן (
להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.
התפקידים המוגדרים מראש האלה מכילים את ההרשאות שנדרשות כדי ליצור ספק אימות באמצעות מפתח API ולהשתמש בו. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:
ההרשאות הנדרשות
כדי ליצור ספק אימות באמצעות מפתח API ולהשתמש בו, נדרשות ההרשאות הבאות:
-
כדי ליצור ספקי אימות:
agentidentity.authProviders.create -
כדי להשתמש בספקי אימות:
-
agentidentity.authProviders.retrieveCredentials -
aiplatform.endpoints.predict -
aiplatform.sessions.create
-
יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.
קבלת מפתח API משירות של צד שלישי
לפני שיוצרים ספק אימות, צריך לקבל מפתח API משירות הצד השלישי שאליו רוצים שהסוכן יתחבר.
אם אתם מתחברים לשירות של צד שלישי מחוץ ל- Google Cloud, אתם צריכים לקבל את מפתח ה-API מפורטל המפתחים של השירות הזה ולדלג על השלבים שבקטע הזה.
אם אתם מתחברים ל Google Cloud שירותים (כמו Cloud Translation או מפות Google), אתם יכולים ליצור ולשנות מפתח API באמצעות השלבים הבאים:
-
במסוף Google Cloud , מפעילים את שירותי ה-API הנדרשים בפרויקט:
- במסוף Google Cloud , נכנסים לדף APIs & Services >Library.
- מחפשים ומפעילים את ממשקי ה-API שבהם הסוכן משתמש, כמו Cloud Translation API או Google Maps Weather API.
- מעתיקים את מחרוזת מפתח ה-API שנוצרה.
מגדירים את מפתח ה-API:
- במסוף Google Cloud , נכנסים לדף APIs & Services >Credentials.
- לוחצים על Create credentials >API Key.
- בתיבת הדו-שיח Create API key (יצירת מפתח API), מבצעים את הפעולות הבאות:
- מזינים שם ייחודי למפתח ה-API.
- כדי להגביל את המפתח לממשקי ה-API הספציפיים שהפעלתם, בוחרים את ממשקי ה-API האלה מהרשימה Select API restrictions.
- אופציונלי: בקטע Restrict your key to reduce security risks, בוחרים סוג אפליקציה כדי להגביל את הגישה.
- לוחצים על יצירה.
-
כדי לאמת את מפתח ה-API, שולחים בקשת בדיקה לנקודת הקצה של השירות.
-
כדי לאמת מפתח Cloud Translation API, מריצים את הפקודה הבאה:
curl -X POST \ -H "Content-Type: application/json" \ -H "X-goog-api-key:
YOUR_API_KEY" \ -d '{"q": "Hello world", "target": "es"}' \ "https://translation.googleapis.com/language/translate/v2"מחליפים את הערך
YOUR_API_KEYבמפתח ה-API שיצרתם. -
כדי לאמת מפתח Google Maps Weather API, מריצים את הפקודה הבאה:
curl -X GET \ "https://weather.googleapis.com/v1/currentConditions:lookup?key=
YOUR_API_KEY&location.latitude=37.4220&location.longitude=-122.0841"מחליפים את הערך
YOUR_API_KEYבמפתח ה-API שיצרתם.
אם מפתח ה-API תקין והוגדר בצורה נכונה, השירות מחזיר את הנתונים המבוקשים.
-
יצירת ספק אימות באמצעות מפתח API
יוצרים ספק אימות כדי להגדיר את ההגדרות ואת פרטי הכניסה לאפליקציות של צד שלישי.
אימות בקוד הסוכן
כדי לאמת את הנציג, אפשר להשתמש ב-ADK.
ADK
מפנים לספק האימות בקוד של הסוכן באמצעות ערכת הכלים של MCP ב-ADK.
from google.adk.agents.llm_agent import LlmAgent from google.adk.auth.credential_manager import CredentialManager from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams from google.adk.tools.mcp_tool.mcp_toolset import McpToolset from google.adk.auth.auth_tool import AuthConfig # Register Google Cloud auth provider CredentialManager.register_auth_provider(GcpAuthProvider()) # Create Google Cloud auth provider scheme # Note: If using the legacy V1 API, the resource name uses 'connectors' # instead of 'authProviders': projects/.../connectors/... auth_scheme = GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME" ) # Configure an MCP tool with the authentication scheme. toolset = McpToolset( connection_params=StreamableHTTPConnectionParams(url="https://YOUR_MCP_SERVER_URL"), auth_scheme=auth_scheme, ) # Initialize the agent with the authenticated tools. agent = LlmAgent( name="AGENT_NAME", model="gemini-2.5-flash", instruction="AGENT_INSTRUCTIONS", tools=[toolset], )
דוגמה: התחברות ל-MCP של מפות Google
בדוגמה הבאה מוצגת הגדרת agent.py שמקשרת סוכן לשרת MCP של מפות Google:
import os from google.adk.agents import Agent from google.adk.apps import App from google.adk.auth.credential_manager import CredentialManager from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme from google.adk.models import Gemini from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams from google.adk.tools.mcp_tool.mcp_toolset import McpToolset os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID" os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True" # Register Google Cloud auth provider for Agent Identity Credentials service CredentialManager.register_auth_provider(GcpAuthProvider()) maps_auth_scheme = GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME" ) maps_tools = McpToolset( connection_params=StreamableHTTPConnectionParams(url="https://mapstools.googleapis.com/mcp"), auth_scheme=maps_auth_scheme, errlog=None, ) root_agent = Agent( name="root_agent", model=Gemini(model="gemini-2.5-flash"), instruction=( "You are a helpful AI assistant designed to provide accurate and useful " "information. You can also use your Google Maps tools to look up " "locations and directions." ), tools=[maps_tools], ) app = App( root_agent=root_agent, name="AGENT_NAME", )
ADK
אפשר להפנות לספק האימות בקוד של הסוכן באמצעות כלי פונקציה מאומת ב-ADK.
import httpx from google.adk.agents.llm_agent import LlmAgent from google.adk.auth.credential_manager import CredentialManager from google.adk.integrations.agent_identity import GcpAuthProvider from google.adk.integrations.agent_identity import GcpAuthProviderScheme from google.adk.apps import App from google.adk.auth.auth_credential import AuthCredential from google.adk.auth.auth_tool import AuthConfig from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool from vertexai import agent_engines # First, register Google Cloud auth provider CredentialManager.register_auth_provider(GcpAuthProvider()) # Create Auth Config # Note: If using the legacy V1 API, the resource name uses 'connectors' # instead of 'authProviders': projects/.../connectors/... spotify_auth_config = AuthConfig( auth_scheme=GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME" ) ) # Use the Auth Config in Authenticated Function Tool spotify_search_track_tool = AuthenticatedFunctionTool( func=spotify_search_track, auth_config=spotify_auth_config ) # Sample function tool async def spotify_search_track(credential: AuthCredential, query: str) -> str | list: token = None if credential.http and credential.http.credentials: token = credential.http.credentials.token if not token: return "Error: No authentication token available." async with httpx.AsyncClient() as client: response = await client.get( "https://api.spotify.com/v1/search", headers={"Authorization": f"Bearer {token}"}, params={"q": query, "type": "track", "limit": 1}, ) # Add your own logic here agent = LlmAgent( name="AGENT_NAME", model="gemini-2.5-flash", instruction="AGENT_INSTRUCTIONS", tools=[spotify_search_track_tool], ) app = App( name="APP_NAME", root_agent=agent, ) vertex_app = agent_engines.AdkApp(app_name=app)
דוגמה: התחברות ל-Google Maps Weather API
בדוגמה הבאה מוצגת הגדרה של agent.py שמקשרת סוכן ל-Google Maps Weather API באמצעות כלי פונקציה מאומת:
import os import httpx from google.adk.agents import Agent from google.adk.apps import App from google.adk.auth.auth_credential import AuthCredential from google.adk.auth.auth_tool import AuthConfig from google.adk.auth.credential_manager import CredentialManager from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme from google.adk.models import Gemini from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID" os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True" # Register Google Cloud auth provider for Agent Identity Credentials service CredentialManager.register_auth_provider(GcpAuthProvider()) weather_auth_config = AuthConfig( auth_scheme=GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME" ) ) async def get_weather(credential: AuthCredential, latitude: float, longitude: float) -> str | dict: """Gets current weather conditions for a location.""" api_key = None if http := credential.http: if http.additional_headers and "X-GOOG-API-KEY" in http.additional_headers: api_key = http.additional_headers["X-GOOG-API-KEY"] elif http.credentials and http.credentials.token: api_key = http.credentials.token if not api_key: return "Error: No API key available from the auth provider." params = {"location.latitude": latitude, "location.longitude": longitude, "key": api_key} async with httpx.AsyncClient() as client: response = await client.get( "https://weather.googleapis.com/v1/currentConditions:lookup", params=params, ) if response.status_code != 200: return f"Error from Weather API: {response.status_code} - {response.text}" return response.json() get_weather_tool = AuthenticatedFunctionTool( func=get_weather, auth_config=weather_auth_config ) root_agent = Agent( name="root_agent", model=Gemini(model="gemini-2.5-flash"), instruction=( "You are a helpful AI assistant. You will use your weather tool to " "look up current conditions." ), tools=[get_weather_tool], ) app = App( root_agent=root_agent, name="AGENT_NAME", )
ADK
מפנים לספק האימות בקוד של הסוכן באמצעות ערכת הכלים Agent Registry MCP ב-ADK.
from google.adk.agents.llm_agent import LlmAgent from google.adk.auth.credential_manager import CredentialManager from google.adk.integrations.agent_identity import GcpAuthProvider from google.adk.integrations.agent_identity import GcpAuthProviderScheme from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams from google.adk.tools.mcp_tool.mcp_toolset import McpToolset from google.adk.auth.auth_tool import AuthConfig from google.adk.integrations.agent_registry import AgentRegistry # First, register Google Cloud auth provider CredentialManager.register_auth_provider(GcpAuthProvider()) # Create Google Cloud auth provider scheme # Note: If using the legacy V1 API, the resource name uses 'connectors' # instead of 'authProviders': projects/.../connectors/... auth_scheme = GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME" ) # Set Agent Registry registry = AgentRegistry(project_id="PROJECT_ID", location="global") toolset = registry.get_mcp_toolset( mcp_server_name=( "projects/PROJECT_ID/locations/" "global/mcpServers/" "agentregistry-00000000-0000-0000-0000-000000000000" ), auth_scheme=auth_scheme, ) # Example MCP tool toolset = McpToolset( connection_params=StreamableHTTPConnectionParams(url="MCP_URL"), auth_scheme=auth_scheme, ) agent = LlmAgent( name="AGENT_NAME", model="MODEL_NAME", instruction="AGENT_INSTRUCTIONS", tools=[toolset], )
פריסת הסוכן
כשפורסים את הסוכן ב- Google Cloud, חשוב לוודא שאימות הזהות של הסוכן מופעל.
אם אתם פורסים ל-Agent Runtime ב-Gemini Enterprise Agent Platform, צריך להשתמש בדגל identity_type=AGENT_IDENTITY:
import vertexai
from vertexai import types
from vertexai.agent_engines import AdkApp
# Initialize the Vertex AI client with v1beta1 API for Agent Identity support
client = vertexai.Client(
project="PROJECT_ID",
location="LOCATION",
http_options=dict(api_version="v1beta1")
)
# Use the proper wrapper class for your Agent Framework (e.g., AdkApp)
app = AdkApp(agent=agent)
# Deploy the agent with Agent Identity enabled
remote_app = client.agent_engines.create(
agent=app,
config={
"identity_type": types.IdentityType.AGENT_IDENTITY,
"requirements": ["google-cloud-aiplatform[agent_engines,adk]", "google-adk[agent-identity]"],
},
)
המאמרים הבאים
- פתרון בעיות באימות של זהות הנציג
- סקירה כללית בנושא זהות הסוכן
- אימות באמצעות OAuth תלת-רגלי עם מנהל ההרשאות
- אימות באמצעות OAuth דו-רגלי עם מנהל ההרשאות
- ניהול ספקי אימות של זהויות סוכנים