Prima di iniziare
Questo tutorial presuppone che tu abbia letto e seguito le istruzioni riportate in:
- Sviluppa un agente Agent Development Kit: per sviluppare
agent
come istanza diAdkApp
. - Autenticazione utente per l'autenticazione come utente per interrogare l'agente.
- Importa e inizializza l'SDK per inizializzare il client per ottenere un'istanza di cui è stato eseguito il deployment (se necessario).
Recupera un'istanza di un agente
Per eseguire una query su un AdkApp
, devi prima
creare una nuova istanza o
recuperare un'istanza esistente.
Per ottenere l'AdkApp
corrispondente a un ID risorsa specifico:
SDK Vertex AI per Python
Esegui questo codice:
import vertexai
client = vertexai.Client( # For service interactions via client.agent_engines
project="PROJECT_ID",
location="LOCATION",
)
adk_app = client.agent_engines.get(name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
print(adk_app)
dove
PROJECT_ID
è l'ID progetto Google Cloud in cui sviluppi ed esegui il deployment degli agenti,LOCATION
è una delle regioni supportate eRESOURCE_ID
è l'ID dell'agente di cui è stato eseguito il deployment come risorsareasoningEngine
.
Libreria delle richieste Python
Esegui questo codice:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.get(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID
Quando utilizzi l'SDK Vertex AI per Python, l'oggetto adk_app
corrisponde a una
classe AgentEngine
che contiene quanto segue:
- un
adk_app.api_resource
con informazioni sull'agente di cui è stato eseguito il deployment. Puoi anche chiamareadk_app.operation_schemas()
per restituire l'elenco delle operazioni supportate daadk_app
. Per maggiori dettagli, vedi Operazioni supportate. - un
adk_app.api_client
che consente interazioni di servizio sincrone - un
adk_app.async_api_client
che consente interazioni di servizio asincrone
Il resto di questa sezione presuppone che tu abbia un'istanza AgentEngine
denominata adk_app
.
Operazioni supportate
Per AdkApp
sono supportate le seguenti operazioni:
async_stream_query
: per lo streaming di una risposta a una query.async_create_session
: per creare una nuova sessione.async_list_sessions
: per elencare le sessioni disponibili.async_get_session
: per recuperare una sessione specifica.async_delete_session
: per eliminare una sessione specifica.async_add_session_to_memory
: per generare i ricordi di una sessione.async_search_memory
: per recuperare i ricordi.
Per elencare tutte le operazioni supportate:
SDK Vertex AI per Python
Esegui questo codice:
adk_app.operation_schemas()
Libreria delle richieste Python
Esegui questo codice:
import json
json.loads(response.content).get("spec").get("classMethods")
API REST
Rappresentato in spec.class_methods
dalla risposta alla richiesta cURL.
Gestire le sessioni
AdkApp
utilizza sessioni gestite basate sul cloud dopo il deployment dell'agente in Vertex AI Agent Engine. Questa sezione descrive come utilizzare le sessioni gestite.
Creare una sessione
Per creare una sessione per un utente:
SDK Vertex AI per Python
session = await adk_app.async_create_session(user_id="USER_ID")
print(session)
Libreria delle richieste Python
Esegui questo codice:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
import json
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.post(
f"https://{adk_app.api_client.api_endpoint}/v1/{adk_app.resource_name}:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "async_create_session",
"input": {"user_id": "USER_ID"},
}),
)
print(response.content)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{"class_method": "async_create_session", "input": {"user_id": "USER_ID"},}'
USER_ID: scegli il tuo ID utente con un limite di 128 caratteri. Ad esempio,
user-123
.
La sessione viene creata come rappresentazione del dizionario di un oggetto sessione ADK.
Elenco sessioni
Per elencare le sessioni di un utente:
SDK Vertex AI per Python
response = await adk_app.async_list_sessions(user_id="USER_ID"):
for session in response.sessions:
print(session)
Libreria delle richieste Python
Esegui questo codice:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
import json
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.post(
f"https://{adk_app.api_client.api_endpoint}/v1/{adk_app.resource_name}:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "async_list_sessions",
"input": {"user_id": "USER_ID"},
}),
)
print(response.content)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{"class_method": "async_list_sessions", "input": {"user_id": "USER_ID"},}'
dove USER_ID è l'ID utente che hai definito. Ad esempio, user-123
.
Se vengono restituite sessioni, queste utilizzano la forma di dizionario di un oggetto sessione ADK.
Recuperare una sessione
Per ottenere una sessione specifica, devi disporre sia dell'ID utente sia dell'ID sessione:
SDK Vertex AI per Python
session = await adk_app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")
print(session)
Libreria delle richieste Python
Esegui questo codice:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
import json
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.post(
f"https://{adk_app.api_client.api_endpoint}/v1/{adk_app.resource_name}:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "async_get_session",
"input": {"user_id": "USER_ID", "session_id": "SESSION_ID"},
}),
)
print(response.content)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{"class_method": "async_get_session", "input": {"user_id": "USER_ID", "session_id": "SESSION_ID"},}'
session
è la rappresentazione del dizionario di un
oggetto sessione ADK.
Eliminare una sessione
Per eliminare una sessione, devi disporre sia dell'ID utente sia dell'ID sessione:
SDK Vertex AI per Python
await adk_app.async_delete_session(user_id="USER_ID", session_id="SESSION_ID")
Libreria delle richieste Python
Esegui questo codice:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
import json
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.post(
f"https://{adk_app.api_client.api_endpoint}/v1/{adk_app.resource_name}:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "async_delete_session",
"input": {"user_id": "USER_ID", "session_id": "SESSION_ID"},
}),
)
print(response.content)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{"class_method": "async_delete_session", "input": {"user_id": "USER_ID", "session_id": "SESSION_ID"},}'
Trasmettere in streaming una risposta a una query
Per trasmettere in streaming le risposte di un agente in una sessione:
SDK Vertex AI per Python
async for event in adk_app.async_stream_query(
user_id="USER_ID",
session_id="SESSION_ID", # Optional
message="What is the exchange rate from US dollars to SEK today?",
):
print(event)
Libreria delle richieste Python
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
requests.post(
f"https://{adk_app.api_client.api_endpoint}/v1/{adk_app.resource_name}:streamQuery",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "async_stream_query",
"input": {
"user_id": "USER_ID",
"session_id": "SESSION_ID",
"message": "What is the exchange rate from US dollars to SEK today?",
},
}),
stream=True,
)
API REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse -d '{
"class_method": "async_stream_query",
"input": {
"user_id": "USER_ID",
"session_id": "SESSION_ID",
"message": "What is the exchange rate from US dollars to SEK today?",
}
}'
Se utilizzi l'SDK Vertex AI per Python, dovresti ricevere una continuazione della conversazione come la seguente sequenza di dizionari:
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
'currency_from': 'USD',
'currency_to': 'SEK'},
'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate'}}],
'role': 'model'},
'id': 'bOPHtzji',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_response': {'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate',
'response': {'amount': 1.0,
'base': 'USD',
'date': '2025-04-03',
'rates': {'SEK': 9.6607}}}}],
'role': 'user'},
'id': '9AoDFmiL',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
'2025-04-03 is 1 USD to 9.6607 SEK.'}],
'role': 'model'},
'id': 'hmle7trT',
# ...
}
Gestire i ricordi
AdkApp
utilizza Vertex AI Agent Engine Memory Bank
se includi un PreloadMemoryTool
nella definizione dell'agente
e lo implementi in Vertex AI Agent Engine. Questa sezione
descrive come utilizzare la generazione e il recupero di ricordi dall'agente tramite
l'implementazione predefinita del
servizio di memoria ADK.
Aggiungere una sessione a un ricordo
Per conservare la memoria di informazioni significative in una sessione (che possono essere utilizzate in sessioni future), utilizza il metodo async_add_session_to_memory
:
SDK Vertex AI per Python
await adk_app.async_add_session_to_memory(session="SESSION_DICT")
dove SESSION_DICT
è la forma del dizionario di un
oggetto sessione ADK.
Cercare ricordi
Per cercare nelle memorie dell'agente, puoi utilizzare il metodo
async_search_memory
:
SDK Vertex AI per Python
response = await adk_app.async_search_memory(
user_id="USER_ID",
query="QUERY",
)
print(response)
dove
USER_ID
è l'ambito dei ricordi pertinenti.QUERY
è la query per cui eseguire la ricerca di similarità.
Passaggi successivi
- Utilizzare un agente.
- Valuta un agente.
- Gestisci gli agenti di cui è stato eseguito il deployment.
- Richiedere assistenza.