Utilizza un agente ADK

Prima di iniziare

Questo tutorial presuppone che tu abbia letto e seguito le istruzioni riportate in:

Ottieni un'istanza di un agente

Per eseguire query su un AdkApp, devi prima creare una nuova istanza o recuperare un'istanza esistente.

Per ottenere il AdkApp corrispondente a un ID risorsa specifico:

SDK Agent Platform

Esegui questo codice:

import agentplatform

client = agentplatform.Client(  # For service interactions via client.runtimes
    project="PROJECT_ID",
    location="LOCATION",
)

adk_app = client.runtimes.get(name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

print(adk_app)

dove

Libreria di 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 Agent Platform, l'oggetto adk_app corrisponde a una classe AgentRuntime che contiene quanto segue:

Il resto di questa sezione presuppone che tu abbia un'istanza AgentRuntime denominata adk_app.

Operazioni supportate

Per AdkApp sono supportate le seguenti operazioni:

Per elencare tutte le operazioni supportate:

SDK Agent Platform

Esegui questo codice:

adk_app.operation_schemas()

Libreria di 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.

Gestisci le sessioni

AdkApp utilizza sessioni gestite basate su cloud dopo il deployment dell'agente su Agent Platform. Questa sezione descrive come utilizzare le sessioni gestite.

Crea una sessione

Per creare una sessione per un utente, utilizza il metodo AdkApp.async_create_session:

SDK Agent Platform

session = await adk_app.async_create_session(user_id="USER_ID")

print(session)

Libreria di 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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID: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 caratteri di 128. Ad esempio, user-123.

La sessione viene creata come rappresentazione del dizionario di un oggetto sessione ADK.

Elenca sessioni

Per elencare le sessioni di un utente, utilizza il metodo AdkApp.async_list_sessions:

SDK Agent Platform

response = await adk_app.async_list_sessions(user_id="USER_ID"):
for session in response.sessions:
    print(session)

Libreria di 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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID: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.

Recupera una sessione

Per ottenere una sessione specifica, utilizza il metodo AdkApp.async_get_session:

SDK Agent Platform

session = await adk_app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")

print(session)

Libreria di 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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID: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.

Elimina una sessione

Per eliminare una sessione, utilizza il metodo AdkApp.async_delete_session:

SDK Agent Platform

await adk_app.async_delete_session(user_id="USER_ID", session_id="SESSION_ID")

Libreria di 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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID: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"},}'

Trasmetti in streaming una risposta a una query

Per trasmettere in streaming le risposte di un agente in una sessione, utilizza il metodo AdkApp.async_stream_query:

SDK Agent Platform

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 di richieste Python

from google import auth as google_auth
from google.auth.transport import requests as google_requests
import json
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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse",
    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",
    "message": "What is the exchange rate from US dollars to SEK today?"
  }
}'

Se utilizzi l'SDK Agent Platform, 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',
 # ...
}

Gestisci gli errori di streaming

Se si verifica un errore prima dell'inizio dello streaming, :streamQuery restituisce una risposta di errore HTTP standard non 200. Una volta che la piattaforma dell'agente inizia a trasmettere gli eventi, l'intestazione dello stato HTTP 200 OK è già stata inviata e non può essere modificata. Se si verifica un errore durante lo stream (ad esempio un'eccezione non gestita, un limite di frequenza downstream o una richiesta in uscita non autorizzata), Agent Platform scrive un chunk di errore JSON finale (un frame di errore terminale) e chiude lo stream:

{
  "code": 429,
  "message": "429 RESOURCE_EXHAUSTED...",
  "errorCode": "429",
  "errorMessage": "429 RESOURCE_EXHAUSTED..."
}

Quando analizzi le risposte, distingui tra i due tipi di errori che possono apparire nello stream:

  • Frame di errore di runtime del terminale: contiene solo campi di errore che utilizzano camelCase (errorCode e errorMessage e, facoltativamente, code e message) senza metadati degli eventi. Dopo questo frame, lo stream viene chiuso.
  • Errore evento ADK: utilizza snake_case (error_code e error_message) all'interno di un oggetto evento ADK standard insieme ai campi dei metadati come id, invocation_id e author.

Se chiami :streamQuery direttamente con requests o curl, controlla ogni blocco analizzato per verificare la presenza di frame di errore terminale, anziché presumere che HTTP 200 OK significhi che la query è riuscita. Per saperne di più sui formati dei frame di errore terminale e sulle indicazioni per i nuovi tentativi, consulta Gestisci gli errori di streaming.

Esegui query sull'agente con contenuti multimodali

Per inviare contenuti non testuali o multimodali (come immagini, video, audio o documenti) all'agente, passa un dizionario che rappresenta un oggetto types.Content al parametro message= di async_stream_query (o chiama content.model_dump(exclude_none=True, mode="json") su un'istanza types.Content). Per i file archiviati in Cloud Storage, specifica file_data con file_uri e mime_type in parts:

SDK Agent Platform

video_message = {
    "role": "user",
    "parts": [
        {
            "file_data": {
                "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
                "mime_type": "video/mp4",
            },
        },
        {
            "text": "Describe the attached media in 5 words!",
        },
    ],
}

async for event in adk_app.async_stream_query(
    user_id="USER_ID",
    #session_id="SESSION_ID",  # Optional
    message=video_message,
):
  print(event)

Libreria di richieste Python

from google import auth as google_auth
from google.auth.transport import requests as google_requests
import json
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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse",
    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": {
                "role": "user",
                "parts": [
                    {
                        "file_data": {
                            "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
                            "mime_type": "video/mp4",
                        },
                    },
                    {
                        "text": "Describe the attached media in 5 words!",
                    },
                ],
            },
        },
    }),
    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",
    "message": {
      "role": "user",
      "parts": [
        {
          "file_data": {
            "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
            "mime_type": "video/mp4"
          }
        },
        {
          "text": "Describe the attached media in 5 words!"
        }
      ]
    }
  }
}'

Per l'elenco dei tipi MIME supportati da Gemini, consulta la documentazione su:

Job di query a lunga esecuzione

Per le query che possono richiedere molto tempo per essere completate (fino a sette giorni), puoi eseguirle come job a lunga esecuzione. Questi job vengono eseguiti in modo asincrono. Puoi controllare lo stato del job e recuperare i risultati in un secondo momento.

Esegui il deployment di un agente per le query asincrone

Per eseguire il deployment di un agente, segui le istruzioni generali riportate in Esegui il deployment di un agente. Per il deployment basato sull'origine, imposta il campo deploymentSpec.agentFramework su google-adk.

Se utilizzi un endpoint API personalizzato creando la tua immagine container, devi aggiungere le seguenti variabili di ambiente durante la creazione dell'agente utilizzando l'SDK:

"env_vars" = {
    "API_ENDPOINT_PREFIX": "/api/myendpoint"
}

Avvia un job di query a lunga esecuzione

Come prerequisito, concedi all'identità di runtime configurata dell'agente (preferendo un'identità dell'agente isolata o un service account personalizzato dedicato; utilizza l'agente di servizio AI Platform Reasoning Engine predefinito service-PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com solo se l'agente viene eseguito con l'agente di servizio predefinito) sia roles/storage.objectCreator (per scrivere l'output) sia roles/storage.objectViewer (per leggere la query di input temporanea) nel bucket di archiviazione quando l'input e l'output condividono un bucket, o roles/storage.objectViewer nel bucket di input e roles/storage.objectCreator nel bucket di output quando sono separati. (roles/storage.objectCreator da solo è sufficiente in una configurazione con lo stesso bucket solo se utilizzi l'agente di servizio gcp-sa-aiplatform-re predefinito, che ha già storage.objects.get nel progetto dell'agente.)

Per avviare un job di query a lunga esecuzione:

SDK Agent Platform

import agentplatform

client = agentplatform.Client(
    project="PROJECT_ID",
    location="LOCATION",
)

response = client.runtimes.run_query_job(
    name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
    config={
        "query": '{"input":{"user_id":"USER_ID", "message":"What is the exchange rate from US dollars to SEK today?"}}',
        "output_gcs_uri": "gs://GCS_BUCKET_NAME/OUTPUT_FILE",
    },
)
print(response)

Con l'SDK, output_gcs_uri può essere una directory o un nome file. Se si tratta di un nome file, il sistema utilizza questo file per archiviare la risposta. Se si tratta di una directory, il sistema genera automaticamente un file per la risposta. In entrambi i casi, la query di input viene archiviata nella stessa directory con lo stesso prefisso del nome file del file di output.

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:asyncQuery -d \
'{
  "input_gcs_uri": "gs://GCS_BUCKET_NAME/INPUT_FILE",
  "output_gcs_uri": "gs://GCS_BUCKET_NAME/OUTPUT_FILE"
}'

Per la chiamata API REST, il campo input_gcs_uri deve puntare a un file che contiene la query. Il contenuto del file deve essere un oggetto JSON con un campo input che corrisponde al campo input di QueryReasoningEngineRequest (ad esempio { "input": { "user_id": "hello", "message":"$QUERY"} }). Se questo file di input si trova in un bucket diverso dalla posizione di output (o se l'agente utilizza un'identità agente isolata o un service account personalizzato dedicato anziché l'agente di servizio service-PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com predefinito), assicurati che l'identità di runtime configurata dell'agente disponga del ruolo roles/storage.objectViewer nel bucket di archiviazione in cui si trovano i file di input.

output_gcs_uri deve essere un nome file.

Controlla lo stato di un job di query a lunga esecuzione

Per controllare lo stato e recuperare i risultati di un job di query a lunga esecuzione:

SDK Agent Platform

response = client.runtimes.check_query_job(
    name="JOB_NAME",
    config={
        "retrieve_result": True,
    },
)
print(response)

Annulla un job di query a lunga esecuzione

Per annullare un job di query a lunga esecuzione, devi avere il nome della risorsa LRO restituito dal job di query a lunga esecuzione.

SDK Agent Platform

response = client.runtimes.cancel_query_job(
    name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
    config={
        "operation_name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
    },
)

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:cancelAsyncQuery -d \
'{
  "name": "projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
  "operation_name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"
}'

L'annullamento è asincrono. La richiesta di annullamento viene restituita non appena viene accettata, ma il job può continuare a segnalare lo stato RUNNING da check_query_job fino al termine del lavoro già in corso, ad esempio una chiamata allo strumento di blocco.

Una volta annullato il job, la sua operazione viene completata con un codice di errore 1 (CANCELLED) e il messaggio Cancelled by user.. Tieni presente che check_query_job segnala ogni operazione completata con un errore come stato FAILED, quindi un job annullato viene segnalato come FAILED anziché tramite uno stato annullato distinto. Controlla il codice di errore per distinguere un annullamento da un errore effettivo.

Gestisci i ricordi

AdkApp utilizza Memory Bank se includi un PreloadMemoryTool nella definizione dell'agente ed esegui il deployment dell'agente su Agent Platform. Questa sezione descrive come generare e recuperare i ricordi dall'agente tramite l'implementazione predefinita del servizio di memoria ADK.

Per i callback di generazione della memoria, gli strumenti di recupero e altri runtime, consulta Utilizza Memory Bank con ADK.

Aggiungi la sessione alla memoria

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 Agent Platform

await adk_app.async_add_session_to_memory(session="SESSION_DICT")

dove SESSION_DICT è la forma di dizionario di un oggetto sessione ADK.

Cerca nei ricordi

Per eseguire ricerche nelle memorie dell'agente, puoi utilizzare il metodo async_search_memory:

SDK Agent Platform

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 somiglianze.

Passaggi successivi