En esta guía de inicio rápido, se explica cómo configurar tu proyecto de Google Cloud , instalar el kit de desarrollo de agentes (ADK), configurar un agente básico y ejecutar su interfaz de usuario para desarrolladores.
En esta guía de inicio rápido, se supone que usas un IDE local (VS Code, PyCharm, etcétera) con Python 3.10 o una versión posterior y acceso a la terminal. El agente se ejecuta por completo en tu máquina, lo que se recomienda para el desarrollo de aplicaciones locales.
Antes de comenzar
Completa los siguientes pasos:
Configura un proyecto de Google Cloud
Configura tu Google Cloud proyecto y habilita la API de Vertex AI.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
Configura las credenciales
En tu terminal local, configura y autentica con Google Cloud CLI. Si estás familiarizado con la API de Gemini en Google AI Studio, ten en cuenta que la API de Gemini de Vertex AI usa Identity and Access Management en lugar de claves de API para administrar el acceso.
-
Instala y, luego, inicializa Google Cloud CLI.
-
Si ya instalaste gcloud CLI, ejecuta este comando para asegurarte de que los componentes de
gcloud
estén actualizados.gcloud components update
-
Ejecuta el siguiente comando para generar un archivo de credenciales predeterminadas de la aplicación (ADC) local. Tu agente usará estas credenciales para acceder a Vertex AI durante el desarrollo de la aplicación local.
gcloud auth application-default login
Para obtener más información, consulta Configura credenciales predeterminadas de la aplicación.
Configura un entorno virtual y, luego, instala el ADK
Crea y activa un entorno virtual (recomendado):
# Create python -m venv .venv # Activate (uncomment the line relevant to your environment) # macOS/Linux: source .venv/bin/activate # Windows CMD: .venv\Scripts\activate.bat # Windows PowerShell: .venv\Scripts\Activate.ps1
Instala el ADK:
pip install google-adk
Crear un agente
Usa la terminal para crear la estructura de carpetas:
mkdir multi_tool_agent/
touch \
multi_tool_agent/__init__.py \
multi_tool_agent/agent.py \
multi_tool_agent/.env
Tu estructura:
parent_folder/
multi_tool_agent/
__init__.py
agent.py
.env
Copia y pega el siguiente código en los tres archivos que creaste:
__init__.py
from . import agent
.env
# If using Gemini via Vertex AI on Google CLoud
GOOGLE_CLOUD_PROJECT="your-project-id"
GOOGLE_CLOUD_LOCATION="your-location" #e.g. us-central1
GOOGLE_GENAI_USE_VERTEXAI="True"
agent.py
from google.adk.agents import Agent
def get_weather(city: str) -> dict:
"""Retrieves the current weather report for a specified city.
Returns:
dict: A dictionary containing the weather information with a 'status' key ('success' or 'error') and a 'report' key with the weather details if successful, or an 'error_message' if an error occurred.
"""
if city.lower() == "new york":
return {"status": "success",
"report": "The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit)."}
else:
return {"status": "error",
"error_message": f"Weather information for '{city}' is not available."}
def get_current_time(city:str) -> dict:
"""Returns the current time in a specified city.
Args:
dict: A dictionary containing the current time for a specified city information with a 'status' key ('success' or 'error') and a 'report' key with the current time details in a city if successful, or an 'error_message' if an error occurred.
"""
import datetime
from zoneinfo import ZoneInfo
if city.lower() == "new york":
tz_identifier = "America/New_York"
else:
return {"status": "error",
"error_message": f"Sorry, I don't have timezone information for {city}."}
tz = ZoneInfo(tz_identifier)
now = datetime.datetime.now(tz)
return {"status": "success",
"report": f"""The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}"""}
root_agent = Agent(
name="weather_time_agent",
model="gemini-2.0-flash",
description="Agent to answer questions about the time and weather in a city.",
instruction="I can answer your questions about the time and weather in a city.",
tools=[get_weather, get_current_time]
)
El agente está equipado con dos herramientas de funciones con implementaciones simuladas.
Ejecuta y prueba tu agente
En la terminal, navega al directorio superior del agente (por ejemplo, con
cd ..
):parent_folder/ <-- navigate to this directory multi_tool_agent/ __init__.py agent.py .env
Ejecuta el siguiente comando para iniciar la IU web para desarrolladores.
adk web
Abre la URL proporcionada (por lo general,
http://localhost:8000
ohttp://127.0.0.1:8000
) en tu navegador. Esta conexión permanece por completo en tu máquina local. Seleccionamulti_tool_agent
y, luego, interactúa con el agente.
Ejemplos de instrucciones para probar
Puedes probar las siguientes instrucciones:
- ¿Cómo está el clima en Nueva York?
- ¿Qué hora es en Nueva York?
- ¿Cómo está el clima en París?
- ¿Qué hora es en París?
¿Qué sigue?
Obtén más información sobre los conceptos de los agentes