Sviluppare un agente Agent Development Kit

Questa pagina mostra come sviluppare un agente utilizzando il modello Agent Development Kit (la classe AdkApp nell'SDK Vertex AI per Python). L'agente restituisce il tasso di cambio tra due valute in una data specificata.

Procedi nel seguente modo:

  1. Definire e configurare un modello
  2. Definire e utilizzare uno strumento
  3. Gestire le sessioni

Prima di iniziare

Assicurati che l'ambiente sia configurato seguendo i passaggi descritti in Configurare l'ambiente.

Definire e configurare un modello

Definisci la versione del modello:

model = "gemini-2.0-flash"

(Facoltativo) Configura le impostazioni di sicurezza del modello. Per scoprire di più sulle opzioni disponibili per le impostazioni di sicurezza in Gemini, consulta Configurare gli attributi di sicurezza. Di seguito è riportato un esempio di come configurare le impostazioni di sicurezza:

from google.genai import types

safety_settings = [
    types.SafetySetting(
        category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold=types.HarmBlockThreshold.OFF,
    ),
]

(Facoltativo) Specifica i parametri di generazione dei contenuti:

from google.genai import types


generate_content_config = types.GenerateContentConfig(
   safety_settings=safety_settings,
   temperature=0.28,
   max_output_tokens=1000,
   top_p=0.95,
)

Crea un AdkApp utilizzando le configurazioni del modello:

from google.adk.agents import Agent
from vertexai.preview.reasoning_engines import AdkApp

agent = Agent(
   model=model,                                      # Required.
   name='currency_exchange_agent',                   # Required.
   generate_content_config=generate_content_config,  # Optional.
)
app = AdkApp(agent=agent)

Se esegui il codice in un ambiente interattivo, come il terminale o un blocco note di Colab, puoi eseguire una query come passaggio intermedio di test:

for event in app.stream_query(
   user_id="USER_ID",  # Required
   message="What is the exchange rate from US dollars to Swedish currency?",
):
   print(event)

dove USER_ID è un ID definito dall'utente con un limite di 128 caratteri.

La risposta è un dizionario Python simile al seguente esempio:

{'actions': {'artifact_delta': {},
             'requested_auth_configs': {},
             'state_delta': {}},
 'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'To provide you with the most accurate '
                                'exchange rate, I need to know the specific '
                                'currencies you\'re asking about. "Swedish '
                                'currency" could refer to:\n'
                                '\n'
                                '*   **Swedish Krona (SEK):** This is the '
                                'official currency of Sweden.\n'
                                '\n'
                                "Please confirm if you're interested in the "
                                'exchange rate between USD and SEK. Once you '
                                'confirm, I can fetch the latest exchange rate '
                                'for you.\n'}],
             'role': 'model'},
 'id': 'LYg7wg8G',
 'invocation_id': 'e-113ca547-0f19-4d50-9dde-f76cbc001dce',
 'timestamp': 1744166956.925927}

Definisci e utilizza uno strumento

Dopo aver definito il modello, definisci gli strumenti che utilizza per il ragionamento.

Quando definisci la funzione, è importante includere commenti che descrivano in modo completo e chiaro i parametri della funzione, la sua esecuzione e il valore restituito. Queste informazioni vengono utilizzate dal modello per determinare quale funzione utilizzare. Devi anche testare la funzione localmente per verificare che funzioni.

Utilizza il seguente codice per definire una funzione che restituisce un tasso di cambio:

def get_exchange_rate(
    currency_from: str = "USD",
    currency_to: str = "EUR",
    currency_date: str = "latest",
):
    """Retrieves the exchange rate between two currencies on a specified date.

    Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
    exchange rate data.

    Args:
        currency_from: The base currency (3-letter currency code).
            Defaults to "USD" (US Dollar).
        currency_to: The target currency (3-letter currency code).
            Defaults to "EUR" (Euro).
        currency_date: The date for which to retrieve the exchange rate.
            Defaults to "latest" for the most recent exchange rate data.
            Can be specified in YYYY-MM-DD format for historical rates.

    Returns:
        dict: A dictionary containing the exchange rate information.
            Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
                "rates": {"EUR": 0.95534}}
    """
    import requests
    response = requests.get(
        f"https://api.frankfurter.app/{currency_date}",
        params={"from": currency_from, "to": currency_to},
    )
    return response.json()

Per testare la funzione prima di utilizzarla nell'agente, esegui quanto segue:

get_exchange_rate(currency_from="USD", currency_to="SEK")

La risposta dovrebbe essere simile alla seguente:

{'amount': 1.0, 'base': 'USD', 'date': '2025-04-03', 'rates': {'SEK': 9.6607}}

Per utilizzare lo strumento all'interno del modello AdkApp, aggiungilo all'elenco degli strumenti nell'argomento tools=:

from google.adk.agents import Agent

agent = Agent(
    model=model,                     # Required.
    name='currency_exchange_agent',  # Required.
    tools=[get_exchange_rate],       # Optional.
)

Puoi testare l'agente localmente eseguendo query di test. Esegui il seguente comando per testare l'agente in locale utilizzando dollari statunitensi e corone svedesi:

from vertexai.preview.reasoning_engines import AdkApp

app = AdkApp(agent=agent)
for event in app.stream_query(
    user_id="USER_ID",
    message="What is the exchange rate from US dollars to SEK on 2025-04-03?",
):
    print(event)

La risposta è una sequenza di dizionari simile alla seguente:

{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
                                                   'currency_from': 'USD',
                                                   'currency_to': 'SEK'},
                                          'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
                                          'name': 'get_exchange_rate'}}],
             'role': 'model'},
 'id': 'zFyIaaif',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_response': {'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
                                              'name': 'get_exchange_rate',
                                              'response': {'amount': 1.0,
                                                           'base': 'USD',
                                                           'date': '2025-04-03',
                                                           'rates': {'SEK': 9.6607}}}}],
             'role': 'user'},
 'id': 'u2YR4Uom',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
                                '2025-04-03 is 9.6607.'}],
             'role': 'model'},
 'id': 'q3jWA3wl',
 # ...
}

Gestire le sessioni

AdkApp utilizza sessioni in memoria quando viene eseguito localmente e sessioni gestite basate su cloud dopo aver eseguito il deployment dell'agente in Vertex AI Agent Engine. Questa sezione descrive come configurare l'agente ADK per il funzionamento con le sessioni gestite.

(Facoltativo) Personalizza il database

Se vuoi sostituire il servizio di sessione gestita predefinito con il tuo database, puoi definire una funzione session_service_builder come segue:

def session_service_builder():
  from google.adk.sessions import InMemorySessionService

  return InMemorySessionService()

Passa il database a AdkApp come session_service_builder=:

from vertexai.preview.reasoning_engines import AdkApp

app = AdkApp(
   agent=agent,                                      # Required.
   session_service_builder=session_service_builder,  # Optional.
)

Utilizzare l'agente con le sessioni

Quando esegui l'agente localmente, le istruzioni riportate di seguito utilizzano le sessioni in memoria:

Crea una sessione per l'agente:

session = app.create_session(user_id="USER_ID")

Elenca le sessioni associate al tuo agente:

app.list_sessions(user_id="USER_ID")

Recupera una sessione specifica:

session = app.get_session(user_id="USER_ID", session_id="SESSION_ID")

dove SESSION_ID è l'ID della sessione specifica che vuoi recuperare.

Esegui query sull'agente utilizzando le sessioni:

for event in app.stream_query(
    user_id="USER_ID",
    session_id=SESSION_ID, # Optional. you can pass in the session_id when querying the agent
    message="What is the exchange rate from US dollars to Swedish currency on 2025-04-03?",
):
    print(event)

L'agente potrebbe rispondere con una richiesta di informazioni come la seguente:

{'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'I need to know the Swedish currency code to '
                                'provide you with the exchange rate.'}],
             'role': 'model'},
 'id': 'wIgZAtQ4',
 #...
}

Puoi inviare una risposta all'interno della sessione (ad esempio "SEK") specificando session_id:

for event in app.stream_query(
    user_id="USER_ID",
    session_id=session.id, # Optional. you can pass in the session_id when querying the agent
    message="SEK",
):
    print(event)

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',
 # ...
}

Passaggi successivi