Skip to main content
Article
google-vertex-aiagent-platformgrounded-generationgoogle-searchpythongcpai-agentrag

Build a Search-Grounded Agent with Google Vertex AI Agents

Create a conversational AI agent that uses Google Search to answer questions with up-to-date information. This guide uses the Python SDK to define, deploy, and chat with your agent on Google Cloud.

intermediate30 min5 steps
The play
  1. Set Up Your GCP Environment
    First, enable the Vertex AI API and authenticate your local environment. This allows the Python SDK to interact with your Google Cloud project. Replace `[YOUR_PROJECT_ID]` with your actual project ID.
  2. Define the Agent and its Tools
    In Python, define the agent's configuration. This includes a display name, core instructions, and the tools it can use. We will equip it with the `GoogleSearchRetriever` tool to ground its responses in search results.
  3. Create the Agent Resource
    Use the Vertex AI client to send your agent definition to Google Cloud, creating a persistent agent resource. This makes the agent available for interaction.
  4. Chat with Your Agent
    Now that the agent is live, you can send it a query. The agent will use Google Search to find relevant information and then generate a grounded response.
  5. Clean Up Resources
    To avoid incurring ongoing costs, delete the agent resource from your project after you're done experimenting.
Starter code
import os
from google.cloud import aiplatform_v1beta1 as aiplatform

# --- Configuration ---
# Replace with your Project ID and a valid GCP location (e.g., 'us-central1')
PROJECT_ID = "your-gcp-project-id"
LOCATION = "us-central1"

# Ensure you have authenticated via `gcloud auth application-default login`

def main():
    """Main function to create, chat with, and delete a Vertex AI Agent."""
    if PROJECT_ID == "your-gcp-project-id":
        print("Error: Please update PROJECT_ID with your Google Cloud Project ID.")
        return

    api_endpoint = f"{LOCATION}-aiplatform.googleapis.com"
    client_options = {"api_endpoint": api_endpoint}
    client = aiplatform.AgentServiceClient(client_options=client_options)

    # 1. Define Agent Configuration
    search_tool = aiplatform.Tool(
        google_search_retriever=aiplatform.GoogleSearchRetriever()
    )
    agent_config = aiplatform.Agent(
        display_name="My Search Agent",
        instruction="You are a helpful assistant that answers questions using the provided search tool.",
        tools=[search_tool],
        default_model="gemini-1.5-pro-001"
    )

    # 2. Create the Agent
    parent = f"projects/{PROJECT_ID}/locations/{LOCATION}"
    print(f"Creating agent in {parent}...")
    try:
        create_response = client.create_agent(parent=parent, agent=agent_config)
        agent_resource_name = create_response.name
        print(f"Successfully created agent: {agent_resource_name}")

        # 3. Chat with the Agent
        user_query = "What were the key announcements at the last Google I/O?"
        print(f"\nQuerying agent with: '{user_query}'")
        chat_response = client.chat_agent(
            name=agent_resource_name,
            user_input=user_query
        )
        print("\nAgent Response:")
        print(chat_response.content)

    except Exception as e:
        print(f"An error occurred: {e}")
        return
    finally:
        # 4. Clean up the agent resource
        if 'agent_resource_name' in locals():
            print(f"\nDeleting agent: {agent_resource_name}")
            client.delete_agent(name=agent_resource_name)
            print("Cleanup complete.")

if __name__ == "__main__":
    main()
Build a Search-Grounded Agent with Google Vertex AI Agents — Action Pack