Utilizzare un agente

Il codice per eseguire query su un agente è lo stesso indipendentemente dal fatto che sia in esecuzione localmente o implementato in remoto. Pertanto, in questa pagina, il termine agent si riferisce a local_agent o remote_agent in modo intercambiabile. Poiché l'insieme di operazioni supportate varia in base ai framework, forniamo istruzioni per l'utilizzo dei modelli specifici per ciascun framework:

Framework Descrizione
LangChain È più facile da usare per i casi d'uso di base grazie alle sue configurazioni e alle sue astrazioni predefinite.
LangGraph Approccio basato su grafici per la definizione dei flussi di lavoro, con funzionalità avanzate di human-in-the-loop e riavvolgimento/riproduzione.
AG2 (in precedenza AutoGen) AG2 fornisce un framework di conversazione multi-agente come astrazione di alto livello per la creazione di flussi di lavoro LLM.

Per gli agenti personalizzati che non si basano su uno dei modelli specifici del framework, puoi seguire questi passaggi:

  1. Autenticazione utente.
  2. Ottieni un'istanza dell'agente.
  3. Cerca le operazioni supportate.
  4. Esegui una query sull'agente.
  5. (Se applicabile) Trasmetti in streaming le risposte dell'agente.

Passaggio 1: autenticazione degli utenti

Segui le stesse istruzioni per la configurazione dell'ambiente.

Passaggio 2: ottieni un'istanza di un agente

Per eseguire una query su un agente, devi prima avere un'istanza di un agente. Puoi creare una nuova istanza o ottenere un'istanza esistente di un agente.

Per ottenere l'agente corrispondente a un ID risorsa specifico:

SDK Vertex AI per Python

Esegui questo codice:

from vertexai import agent_engines

agent = agent_engines.get(RESOURCE_ID)

In alternativa, puoi fornire il nome completo della risorsa dell'agente:

agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

richieste

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()}",
    },
)

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

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

Passaggio 3: operazioni supportate

Quando sviluppi l'agente localmente, hai accesso e conoscenza delle operazioni supportate. Per utilizzare un agente di cui è stato eseguito il deployment, puoi enumerare le operazioni supportate:

SDK Vertex AI per Python

Esegui questo codice:

agent.operation_schemas()

richieste

Esegui questo codice:

import json

json.loads(response.content).get("spec").get("classMethods")

REST

Rappresentato in spec.class_methods dalla risposta alla richiesta curl.

Lo schema di ogni operazione è un dizionario che documenta le informazioni di un metodo per l'agente che puoi chiamare. Di seguito è riportato un esempio di schema di operazione per un'operazione sincrona:

Il seguente comando fornisce un elenco di schemi in formato JSON che corrispondono alle operazioni dell'oggetto remote_app:

agent.operation_schemas()

Ad esempio, di seguito è riportato lo schema dell'operazione query di un LangchainAgent:

{'api_mode': '',
 'name': 'query',
 'description': """Queries the Agent with the given input and config.
    Args:
        input (Union[str, Mapping[str, Any]]):
            Required. The input to be passed to the Agent.
        config (langchain_core.runnables.RunnableConfig):
            Optional. The config (if any) to be used for invoking the Agent.
    Returns:
        The output of querying the Agent with the given input and config.
""",            '        ',
 'parameters': {'$defs': {'RunnableConfig': {'description': 'Configuration for a Runnable.',
                                             'properties': {'configurable': {...},
                                                            'run_id': {...},
                                                            'run_name': {...},
                                                            ...},
                                             'type': 'object'}},
                'properties': {'config': {'nullable': True},
                               'input': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}},
                'required': ['input'],
                'type': 'object'}}

dove

  • name è il nome dell'operazione (ad es. agent.query per un'operazione denominata query).
  • api_mode è la modalità API dell'operazione ("" per sincrono, "stream" per streaming).
  • description è una descrizione dell'operazione basata sulla docstring del metodo.
  • parameters è lo schema degli argomenti di input nel formato dello schema OpenAPI.

Passaggio 4: esegui una query sull'agente

Per eseguire una query sull'agente utilizzando una delle sue operazioni supportate (ad es. query):

SDK Vertex AI per Python

agent.query(input={"messages": [
    ("user", "What is the exchange rate from US dollars to Swedish currency?")
]})

richieste

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://{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({"input": {
        "input": {"messages": [
            ("user", "What is the exchange rate from US dollars to Swedish currency?")
        ]},
    }})
)

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{
  "input": {
    "input": {"messages": [
      ("user", "What is the exchange rate from US dollars to Swedish currency?")
    ]},
  }
}'

La risposta alla query è una stringa simile all'output di un test dell'applicazione locale:

{"input": "What is the exchange rate from US dollars to Swedish currency?",
 # ...
 "output": "For 1 US dollar you will get 10.7345 Swedish Krona."}

Passaggio 5: riproduci in streaming le risposte dell'agente

Se applicabile, puoi riprodurre in streaming una risposta dell'agente utilizzando una delle sue operazioni (ad es. stream_query):

SDK Vertex AI per Python

agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

agent.stream_query(input={"messages": [
    ("user", "What is the exchange rate from US dollars to Swedish currency?")
]})

richieste

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://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{LOCATION}/reasoningEngines/{RESOURCE_ID}:streamQuery",
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {get_identity_token()}",
    },
    data=json.dumps({"input": {
        "input": {"messages": [
            ("user", "What is the exchange rate from US dollars to Swedish currency?")
        ]},
    }}),
    stream=True,
)

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse -d '{
  "input": {
    "input": {"messages": [
      ("user", "What is the exchange rate from US dollars to Swedish currency?")
    ]},
  }
}'

Agent Engine trasmette le risposte sotto forma di sequenza di oggetti generati in modo iterativo. Ad esempio, un insieme di tre risposte potrebbe avere il seguente aspetto:

{'actions': [{'tool': 'get_exchange_rate', ...}]}  # first response
{'steps': [{'action': {'tool': 'get_exchange_rate', ...}}]}  # second response
{'output': 'The exchange rate is 11.0117 SEK per USD as of 2024-12-03.'}  # final response

Passaggi successivi