Desarrolla e implementa agentes en Agent Runtime
Agent Runtime te permite alojar agentes desarrollados con varios frameworks. En este documento, se explica cómo crear, implementar y probar un agente con LangGraph, LangChain, AG2 o LlamaIndex.
En esta guía de inicio rápido, se te guiará por los siguientes pasos:
- Configura tu Google Cloud proyecto
- Instala el SDK de Agent Platform para Python y el framework que elegiste.
- Desarrolla un agente de cambio de divisas.
- Implementa el agente en Agent Runtime.
- Prueba el agente implementado.
Para obtener la guía de inicio rápido con el Kit de desarrollo de agentes (ADK), consulta Desarrolla e implementa agentes en Agent Platform con el Kit de desarrollo de agentes.
Antes de comenzar
- Accede a tu Google Cloud cuenta de. Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
Para obtener los permisos que necesitas para usar Agent Runtime, pídele a tu administrador que te otorgue los siguientes roles de IAM en tu proyecto:
-
Usuario de Agent Platform (
roles/aiplatform.user) -
Administrador de almacenamiento (
roles/storage.admin)
Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.
También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.
Instala e inicializa el SDK de Agent Platform para Python
Ejecuta el siguiente comando para instalar el SDK de Agent Platform para Python y otros paquetes necesarios:
LangGraph
pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,langchain]>=1.112LangChain
pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,langchain]>=1.112AG2
pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,ag2]>=1.112LlamaIndex
pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,llama_index]>=1.112Autentícate como usuario
Colab
Ejecuta el siguiente código:
from google.colab import auth auth.authenticate_user(project_id="PROJECT_ID")Cloud Shell
No se requiere ninguna acción.
Shell local
Ejecuta el siguiente comando:
gcloud auth application-default loginEjecuta el siguiente código para importar Agent Platform y, luego, inicializar el SDK:
(Opcional) Antes de probar un agente que desarrolles, debes importar Agent Platform y, luego, inicializar el SDK de la siguiente manera:
Proyecto de Google Cloud
import vertexai vertexai.init( project="PROJECT_ID", # Your project ID. location="LOCATION", # Your cloud region. )Aquí:
PROJECT_IDes el Google Cloud ID del proyecto en el que desarrollas e implementas agentes.LOCATIONes una de las regiones admitidas.
Antes de implementar un agente, debes importar Agent Platform y, luego, inicializar el SDK de la siguiente manera:
Proyecto de Google Cloud
import vertexai client = vertexai.Client( project="PROJECT_ID", # Your project ID. location="LOCATION", # Your cloud region. )Aquí:
PROJECT_IDes el Google Cloud ID del proyecto en el que desarrollas e implementas agentes.LOCATIONes una de las regiones admitidas.
Desarrolla un agente
Desarrolla una herramienta de cambio de divisas para tu agente:
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.""" import requests response = requests.get( f"https://api.frankfurter.app/{currency_date}", params={"from": currency_from, "to": currency_to}, ) return response.json()Crea una instancia de un agente:
LangGraph
from vertexai import agent_engines agent = agent_engines.LanggraphAgent( model="gemini-2.0-flash", tools=[get_exchange_rate], model_kwargs={ "temperature": 0.28, "max_output_tokens": 1000, "top_p": 0.95, }, )LangChain
from vertexai import agent_engines agent = agent_engines.LangchainAgent( model="gemini-2.0-flash", tools=[get_exchange_rate], model_kwargs={ "temperature": 0.28, "max_output_tokens": 1000, "top_p": 0.95, }, )AG2
from vertexai import agent_engines agent = agent_engines.AG2Agent( model="gemini-2.0-flash", runnable_name="Get Exchange Rate Agent", tools=[get_exchange_rate], )LlamaIndex
from vertexai.preview import reasoning_engines def runnable_with_tools_builder(model, runnable_kwargs=None, **kwargs): from llama_index.core.query_pipeline import QueryPipeline from llama_index.core.tools import FunctionTool from llama_index.core.agent import ReActAgent llama_index_tools = [] for tool in runnable_kwargs.get("tools"): llama_index_tools.append(FunctionTool.from_defaults(tool)) agent = ReActAgent.from_tools(llama_index_tools, llm=model, verbose=True) return QueryPipeline(modules = {"agent": agent}) agent = reasoning_engines.LlamaIndexQueryPipelineAgent( model="gemini-2.0-flash", runnable_kwargs={"tools": [get_exchange_rate]}, runnable_builder=runnable_with_tools_builder, )Prueba el agente localmente:
LangGraph
agent.query(input={"messages": [ ("user", "What is the exchange rate from US dollars to SEK today?"), ]})LangChain
agent.query( input="What is the exchange rate from US dollars to SEK today?" )AG2
agent.query( input="What is the exchange rate from US dollars to SEK today?" )LlamaIndex
agent.query( input="What is the exchange rate from US dollars to SEK today?" )
Implementa un agente
Para implementar el agente, crea un recurso reasoningEngine en Agent Platform:
LangGraph
remote_agent = client.agent_engines.create(
agent,
config={
"requirements": ["google-cloud-aiplatform[agent_engines,langchain]"],
"identity_type": types.IdentityType.AGENT_IDENTITY,
},
)
LangChain
remote_agent = client.agent_engines.create(
agent,
config={
"requirements": ["google-cloud-aiplatform[agent_engines,langchain]"],
"identity_type": types.IdentityType.AGENT_IDENTITY,
},
)
AG2
remote_agent = client.agent_engines.create(
agent,
config={
"requirements": ["google-cloud-aiplatform[agent_engines,ag2]"],
"identity_type": types.IdentityType.AGENT_IDENTITY,
},
)
LlamaIndex
remote_agent = client.agent_engines.create(
agent,
config={
"requirements": ["google-cloud-aiplatform[agent_engines,llama_index]"],
"identity_type": types.IdentityType.AGENT_IDENTITY,
},
)
Usa un agente
Para probar el agente implementado, envía una consulta:
LangGraph
remote_agent.query(input={"messages": [
("user", "What is the exchange rate from US dollars to SEK today?"),
]})
LangChain
remote_agent.query(
input="What is the exchange rate from US dollars to SEK today?"
)
AG2
remote_agent.query(
input="What is the exchange rate from US dollars to SEK today?"
)
LlamaIndex
remote_agent.query(
input="What is the exchange rate from US dollars to SEK today?"
)
Limpia
Sigue estos pasos para evitar que se apliquen cargos a tu Google Cloud cuenta de por los recursos que usaste en esta página.
remote_agent.delete(force=True)
¿Qué sigue?
Configuración del entorno de ejecución de Agent Platform
Configura tu entorno para usar el entorno de ejecución de Agent Platform.
Implementa agentes
Obtén información sobre las cinco formas de implementar un agente en el entorno de ejecución de Agent Platform según tus necesidades de desarrollo.
Administra agentes implementados
Aprende a administrar agentes que se implementaron en el entorno de ejecución administrado de Agent Platform.