Guia de início rápido: criar um agente com o kit de desenvolvimento de agentes

Este guia de início rápido orienta você a configurar seu projeto Google Cloud , instalar o Kit de Desenvolvimento de Agentes (ADK, na sigla em inglês), configurar um agente básico e executar a interface do usuário do desenvolvedor.

Este guia de início rápido pressupõe que você está usando um ambiente de desenvolvimento integrado local (VS Code, PyCharm etc.) com Python 3.10 ou mais recente e acesso ao terminal. O agente é executado inteiramente na sua máquina, o que é recomendado para o desenvolvimento de aplicativos locais.

Antes de começar

Siga estas etapas:

Configurar um projeto do Google Cloud

Configure o projeto Google Cloud e ative a API Vertex AI.

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

Configurar credenciais

No terminal local, configure e faça a autenticação com a CLI do Google Cloud. Se você conhece a API Gemini no Google AI Studio, saiba que a API Gemini do Vertex AI usa o Identity and Access Management em vez de chaves de API para gerenciar o acesso.

  1. Instale e inicialize a Google Cloud CLI.

  2. Se você já instalou a CLI gcloud, execute este comando para garantir que os componentes gcloud estejam atualizados.

    gcloud components update
  3. Execute o comando a seguir para gerar um arquivo local de credenciais padrão do aplicativo (ADC). O agente vai usar essas credenciais para acessar a Vertex AI durante o desenvolvimento de aplicativos locais.

    gcloud auth application-default login

    Para mais informações, consulte Configurar o Application Default Credentials.

Configurar um ambiente virtual e instalar o ADK

  • Crie e ative um ambiente 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
    
  • Instale o ADK:

    pip install google-adk
    

Criar um agente

Usando o terminal, crie a estrutura de pastas:

mkdir multi_tool_agent/
touch \
multi_tool_agent/__init__.py \
multi_tool_agent/agent.py \
multi_tool_agent/.env

Sua estrutura:

parent_folder/
    multi_tool_agent/
        __init__.py
        agent.py
        .env

Copie e cole o seguinte código nos três arquivos criados:

__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]
)

O agente tem duas ferramentas de função com simulações de implementação.

Executar e testar o agente

  1. No terminal, navegue até o diretório pai do agente (por exemplo, usando cd ..):

    parent_folder/      <-- navigate to this directory
        multi_tool_agent/
            __init__.py
            agent.py
            .env
    
  2. Execute o comando abaixo para iniciar a interface da Web para desenvolvedores.

    adk web
    

    Abra o URL fornecido (geralmente http://localhost:8000 ou http://127.0.0.1:8000) no navegador. Essa conexão fica totalmente na sua máquina local. Selecione multi_tool_agent e interaja com o agente.

Exemplos de comandos para testar

Tente as seguintes solicitações:

  • Qual é a previsão do tempo em Nova York?
  • Que horas são em Nova York?
  • Qual é a previsão do tempo em Paris?
  • Que horas são em Paris?

A seguir