{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ijGzTHJJUCPY"
      },
      "outputs": [],
      "source": [
        "# Copyright 2024 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VEqbX8OhE8y9"
      },
      "source": [
        "# Intro to Building and Deploying an Agent with Agent Engine in Vertex AI\n",
        "\n",
        "<table align=\"left\">\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://www.gstatic.com/pantheon/images/bigquery/welcome_page/colab-logo.svg\" alt=\"Google Colaboratory logo\"><br> Run in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://console.cloud.google.com/vertex-ai/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fgemini%2Fagent-engine%2Fintro_agent_engine.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://lh3.googleusercontent.com/JmcxdQi-qOpctIvWKgPtrzZdJJK-J3sWE1RsfjZNwshCFgE_9fULcNpuXYTilIR2hjwN\" alt=\"Google Cloud Colab Enterprise logo\"><br> Run in Colab Enterprise\n",
        "    </a>\n",
        "  </td>      \n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://raw.githubusercontent.com/primer/octicons/refs/heads/main/icons/mark-github-24.svg\" alt=\"GitHub logo\"><br> View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/agent-engine/intro_agent_engine.ipynb\">\n",
        "      <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\"><br> Open in Vertex AI Workbench\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://goo.gle/4jeQzJW\">\n",
        "      <img width=\"32px\" src=\"https://cdn.qwiklabs.com/assets/gcp_cloud-e3a77215f0b8bfa9b3f611c0d2208c7e8708ed31.svg\" alt=\"Google Cloud logo\"><br> Open in  Cloud Skills Boost\n",
        "    </a>\n",
        "  </td>\n",
        "</table>\n",
        "\n",
        "<div style=\"clear: both;\"></div>\n",
        "\n",
        "<b>Share to:</b>\n",
        "\n",
        "<a href=\"https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/8/81/LinkedIn_icon.svg\" alt=\"LinkedIn logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://bsky.app/intent/compose?text=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/7/7a/Bluesky_Logo.svg\" alt=\"Bluesky logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://twitter.com/intent/tweet?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/5a/X_icon_2.svg\" alt=\"X logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://reddit.com/submit?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://redditinc.com/hubfs/Reddit%20Inc/Brand/Reddit_Logo.png\" alt=\"Reddit logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/agent-engine/intro_agent_engine.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg\" alt=\"Facebook logo\">\n",
        "</a>            \n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "84e7e432e6ff"
      },
      "source": [
        "| | |\n",
        "|-|-|\n",
        "|Author(s) | [Kristopher Overholt](https://github.com/koverholt) |"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "CkHPv2myT2cx"
      },
      "source": [
        "## Overview\n",
        "\n",
        "### Gemini\n",
        "\n",
        "Gemini is a family of generative AI models developed by Google DeepMind that is designed for multimodal use cases.\n",
        "\n",
        "### Function Calling in Gemini\n",
        "\n",
        "[Function calling](https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling) lets developers create a description of a function in their code, then pass that description to a language model in a request. The response from the model includes the name of a function that matches the description and the arguments to call it with.\n",
        "\n",
        "### Agent Engine in Vertex AI\n",
        "\n",
        "[Agent Engine](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview) is a managed service that helps you to build and deploy an agent framework. It gives you the flexibility to choose how much reasoning you want to delegate to the LLM and how much you want to handle with customized code. You can define Python functions that get used as tools via [Gemini Function Calling](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling). Agent Engine integrates closely with the Python SDK for the Gemini model in Vertex AI, and it can manage prompts, agents, and examples in a modular way. Agent Engine is compatible with LangChain, LlamaIndex, or other Python frameworks.\n",
        "\n",
        "<img width=\"60%\" src=\"https://storage.googleapis.com/github-repo/generative-ai/gemini/agent-engine/images/agent-engine-overview.png\" alt=\"Agent Engine on Vertex AI\" />"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DrkcqHrrwMAo"
      },
      "source": [
        "### Objectives\n",
        "\n",
        "In this tutorial, you will learn how to build and deploy an agent (model, tools, and reasoning) using the Vertex AI SDK for Python.\n",
        "\n",
        "You'll build and deploy an agent that uses the Gemini model, Python functions as tools, and LangChain for orchestration.\n",
        "\n",
        "You will complete the following tasks:\n",
        "\n",
        "- Install the Vertex AI SDK for Python\n",
        "- Use the Vertex AI SDK to build components of a simple agent\n",
        "- Test your agent locally before deploying\n",
        "- Deploy and test your agent on Vertex AI\n",
        "- Customize each layer of your agent (model, tools, orchestration)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C9nEPojogw-g"
      },
      "source": [
        "### Costs\n",
        "\n",
        "This tutorial uses billable components of Google Cloud:\n",
        "\n",
        "- Vertex AI\n",
        "\n",
        "Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r11Gu7qNgx1p"
      },
      "source": [
        "## Getting Started\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "No17Cw5hgx12"
      },
      "source": [
        "### Install Vertex AI SDK for Python\n",
        "\n",
        "Install the latest version of the Vertex AI SDK for Python as well as extra dependencies related to Agent Engine and LangChain:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "tFy3H3aPgx12"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet \\\n",
        "    \"google-cloud-aiplatform[agent_engines,langchain]\" \\\n",
        "    cloudpickle==3.0.0 \\\n",
        "    \"pydantic>=2.10\" \\\n",
        "    requests"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R5Xep4W9lq-Z"
      },
      "source": [
        "### Restart current runtime\n",
        "\n",
        "To use the newly installed packages in this Jupyter runtime, you must restart the runtime. You can do this by running the cell below, which will restart the current kernel."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "XRvKdaPDTznN"
      },
      "outputs": [],
      "source": [
        "# Restart kernel after installs so that your environment can access the new packages\n",
        "import IPython\n",
        "\n",
        "app = IPython.Application.instance()\n",
        "app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SbmM4z7FOBpM"
      },
      "source": [
        "<div class=\"alert alert-block alert-warning\">\n",
        "<b>⚠️ The kernel is going to restart. Please wait until it is finished before continuing to the next step. ⚠️</b>\n",
        "</div>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dmWOrTJ3gx13"
      },
      "source": [
        "### Authenticate your notebook environment (Colab only)\n",
        "\n",
        "If you are running this notebook on Google Colab, run the following cell to authenticate your environment. This step is not required if you are using [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "NyKGtVQjgx13"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import auth\n",
        "\n",
        "    auth.authenticate_user()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DF4l8DTdWgPY"
      },
      "source": [
        "### Set Google Cloud project information and initialize Vertex AI SDK\n",
        "\n",
        "To get started using Vertex AI, you must have an existing Google Cloud project and [enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
        "\n",
        "Learn more about [setting up a project and a development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "Nqwi-5ufWp_B"
      },
      "outputs": [],
      "source": [
        "PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}\n",
        "LOCATION = \"us-central1\"  # @param {type:\"string\"}\n",
        "STAGING_BUCKET = \"gs://[your-staging-bucket]\"  # @param {type:\"string\"}\n",
        "\n",
        "import vertexai\n",
        "\n",
        "vertexai.init(project=PROJECT_ID, location=LOCATION, staging_bucket=STAGING_BUCKET)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1e5c96372296"
      },
      "source": [
        "## Example: Build and deploy an agent"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jXHfaVS66_01"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "lslYAvw37JGQ"
      },
      "outputs": [],
      "source": [
        "from vertexai import agent_engines\n",
        "from vertexai.preview.reasoning_engines import LangchainAgent"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "43c61bf4c3f5"
      },
      "source": [
        "### Define model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f685ca44c1e9"
      },
      "source": [
        "As you construct your agent from the bottom up, the first component deals with which generative model you want to use in your agent.\n",
        "\n",
        "<img width=\"40%\" src=\"https://storage.googleapis.com/github-repo/generative-ai/gemini/agent-engine/images/agent-stack-1.png\" alt=\"Components of an agent in Agent Engine on Vertex AI\" />\n",
        "\n",
        "Here you'll use the Gemini 2.0 model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "921890fcb875"
      },
      "outputs": [],
      "source": [
        "model = \"gemini-2.0-flash\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "60eba5468448"
      },
      "source": [
        "### Define Python functions (tools)\n",
        "\n",
        "The second component of your agent includes tools and functions, which enable the generative model to interact with external systems, databases, document stores, and other APIs so that the model can get the most up-to-date information or take action with those systems.\n",
        "\n",
        "<img width=\"40%\" src=\"https://storage.googleapis.com/github-repo/generative-ai/gemini/agent-engine/images/agent-stack-2.png\" alt=\"Components of an agent in Agent Engine on Vertex AI\" />\n",
        "\n",
        "In this example, you'll define a function called `get_exchange_rate` that uses the `requests` library to retrieve real-time currency exchange information from an API:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "ff7991bf37bf"
      },
      "outputs": [],
      "source": [
        "def get_exchange_rate(\n",
        "    currency_from: str = \"USD\",\n",
        "    currency_to: str = \"EUR\",\n",
        "    currency_date: str = \"latest\",\n",
        "):\n",
        "    \"\"\"Retrieves the exchange rate between two currencies on a specified date.\"\"\"\n",
        "    import requests\n",
        "\n",
        "    response = requests.get(\n",
        "        f\"https://api.frankfurter.app/{currency_date}\",\n",
        "        params={\"from\": currency_from, \"to\": currency_to},\n",
        "    )\n",
        "    return response.json()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "971f56c167e7"
      },
      "source": [
        "Test the function with sample inputs to ensure that it's working as expected:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "4ae49a2ccd2e"
      },
      "outputs": [],
      "source": [
        "get_exchange_rate(currency_from=\"USD\", currency_to=\"SEK\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "35ca52a9021c"
      },
      "source": [
        "### Define agent\n",
        "\n",
        "The third component of your agent involves adding a reasoning layer, which helps your agent use the tools that you provided to help the end user achieve a higher-level goal.\n",
        "\n",
        "<img width=\"40%\" src=\"https://storage.googleapis.com/github-repo/generative-ai/gemini/agent-engine/images/agent-stack-3.png\" alt=\"Components of an agent in Agent Engine on Vertex AI\" />\n",
        "\n",
        "If you were to use Gemini and Function Calling on their own without a reasoning layer, you would need to handle the process of calling functions and APIs in your application code, and you would need to implement retries and additional logic to ensure that your function calling code is resilient to failures and malformed requests.\n",
        "\n",
        "Here, you'll use the LangChain agent template provided in the Vertex AI SDK for Agent Engine, which brings together the model, tools, and reasoning that you've built up so far:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "68bc1b395f9d"
      },
      "outputs": [],
      "source": [
        "agent = LangchainAgent(\n",
        "    model=model,\n",
        "    tools=[get_exchange_rate],\n",
        "    agent_executor_kwargs={\"return_intermediate_steps\": True},\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fa3c33f6ec72"
      },
      "source": [
        "Now we can test the model and agent behavior to ensure that it's working as expected before we deploy it:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "68a527f87e42"
      },
      "source": [
        "### Test your agent locally\n",
        "\n",
        "With all of the core components of your agent in place, you can send a prompt to your agent using `.query` to test that it's working as expected, including the intermediate steps that the agent performed between the input prompt and the generated summary output. In the default mode, the agent processes your input and returns the **entire agent output in a single response when complete**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "e0c5c699de12"
      },
      "outputs": [],
      "source": [
        "agent.query(input=\"What's the exchange rate from US dollars to Swedish currency today?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b1cf06f5fa46"
      },
      "source": [
        "In addition to the default query mode, the `.stream_query` method allows you to **see the agent's intermediate steps and final output from the chain**.\n",
        "\n",
        "Instead of waiting for the agent to complete all sub-tasks, the agent sends back the response in **chunks as it's being generated**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "7a931f086fc9"
      },
      "outputs": [],
      "source": [
        "message_types = {\"actions\": \"Action\", \"messages\": \"Message\", \"output\": \"Output\"}\n",
        "for chunk in agent.stream_query(\n",
        "    input=\"What's the exchange rate from US dollars to Swedish currency today?\"\n",
        "):\n",
        "    for key, label in message_types.items():\n",
        "        if key in chunk:\n",
        "            print(\"\\n------\\n\")\n",
        "            print(f\"{label}:\")\n",
        "            print()\n",
        "            print(chunk[key])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbe3d34ec106"
      },
      "source": [
        "This allows you to observe the agent's actions in real-time (such as function calls, and intermediate steps), which is helpful for debugging purposes or for providing real-time updates to the end user."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "77b0a9f0d75b"
      },
      "source": [
        "### Deploy your agent on Vertex AI\n",
        "\n",
        "Now that you've specified a model, tools, and reasoning for your agent and tested it out, you're ready to deploy your agent as a remote service in Vertex AI!\n",
        "\n",
        "<img width=\"40%\" src=\"https://storage.googleapis.com/github-repo/generative-ai/gemini/agent-engine/images/agent-stack-4.png\" alt=\"Components of an agent in Agent Engine on Vertex AI\" />\n",
        "\n",
        "You can re-define the agent to avoid any stateful information in the agent due to our testing in the previous cell:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "b2f8365735d2"
      },
      "outputs": [],
      "source": [
        "agent = LangchainAgent(\n",
        "    model=model,\n",
        "    tools=[get_exchange_rate],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ebe2c3be1ca6"
      },
      "source": [
        "Now you're ready to deploy your agent to Agent Engine in Vertex AI by calling `agent_engines.create()` along with:\n",
        "\n",
        "1. The instance of your agent class\n",
        "2. The Python packages and versions that your agent requires at runtime, similar to how you would define packages and versions in a `requirements.txt` file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "id": "fd3b88c73411"
      },
      "outputs": [],
      "source": [
        "remote_agent = agent_engines.create(\n",
        "    agent,\n",
        "    requirements=[\n",
        "        \"google-cloud-aiplatform[agent_engines,langchain]\",\n",
        "        \"cloudpickle==3.0.0\",\n",
        "        \"pydantic>=2.10\",\n",
        "        \"requests\",\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e698a4c3d786"
      },
      "source": [
        "Now you can send a prompt to your remote agent using `.query` to test that it's working as expected:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "d01b37cb77dc"
      },
      "outputs": [],
      "source": [
        "remote_agent.query(\n",
        "    input=\"What's the exchange rate from US dollars to Swedish currency today?\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ff3620f5fa01"
      },
      "source": [
        "Or you can stream the results back from the remote agent interactively using `.stream_query`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "a4250671731e"
      },
      "outputs": [],
      "source": [
        "message_types = {\"actions\": \"Action\", \"messages\": \"Message\", \"output\": \"Output\"}\n",
        "for chunk in remote_agent.stream_query(\n",
        "    input=\"What's the exchange rate from US dollars to Swedish currency today?\"\n",
        "):\n",
        "    for key, label in message_types.items():\n",
        "        if key in chunk:\n",
        "            print(\"\\n------\\n\")\n",
        "            print(f\"{label}:\")\n",
        "            print()\n",
        "            print(chunk[key])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9f2f7d3ed7bd"
      },
      "source": [
        "### Querying your deployed agent\n",
        "\n",
        "You've now deployed your agent and can [interact with it in multiple ways](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/overview), both within this notebook and from other applications or environments. The primary methods for accessing your deployed agent are via the Python client library or through REST API calls. Here's an overview of both methods:\n",
        "\n",
        "**Method 1: Reusing within this notebook or another Python environment**\n",
        "\n",
        "You can directly reuse and query the `remote_agent` instance you created in this notebook.\n",
        "\n",
        "Or, you can instantiate a new instance in another notebook or Python script. To do this, you'll need to retrieve your deployed agent's resource name that uniquely identifies your agent, which is a string that includes the project, location, and Agent Engine ID. You can retrieve it by running the following code in the notebook or environment where you created your agent:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "fdaf8b91413f"
      },
      "outputs": [],
      "source": [
        "remote_agent.resource_name"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "060f8369d113"
      },
      "source": [
        "Use the resource name to load the agent in your other notebook or Python script, then query the remote agent as usual:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "id": "78af4442827e"
      },
      "outputs": [],
      "source": [
        "# from vertexai import agent_engines\n",
        "\n",
        "# AGENT_ENGINE_RESOURCE_NAME = \"YOUR_AGENT_ENGINE_RESOURCE_NAME\"  # Replace with the resource name of your deployed Agent Engine\n",
        "\n",
        "# remote_agent = agent_engines.get(AGENT_ENGINE_RESOURCE_NAME)\n",
        "# response = remote_agent.query(input=query)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "63ab06554fc0"
      },
      "source": [
        "**Method 2: Accessing from other environments via REST API**\n",
        "\n",
        "Beyond the Python client library, your deployed Vertex AI agent can be [queried using REST API calls](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/overview), including:\n",
        "\n",
        "- Python: You can use Python's `requests` library or similar tools to make HTTP calls to the Vertex AI REST API.\n",
        "- cURL: A command-line tool, cURL allows you to send HTTP requests directly. This is useful for testing and debugging.\n",
        "- Other Programming Languages: If you prefer a different language for your application, you can use its native HTTP client library to make REST API calls.\n",
        "\n",
        "In summary, you have access to your deployed agent through the Python client library within Python environments, and more universally through its REST API via tools and programming languages of your choosing."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "82d321fd62e0"
      },
      "source": [
        "## Customizing your agent"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "353d586b9b1b"
      },
      "source": [
        "The example above includes the minimal amount of configuration required for each component within the agent to help you get started.\n",
        "\n",
        "But what if you want to swap to a different Gemini model version, change the generative model parameters or safety filters, or perform additional customizations to the agent? The following example shows some of the most common parameters that you'll want to customize in your agent. Agent Engine in Vertex AI works with [Gemini model versions that support Function Calling](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling) and LangChain agents."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fdda38e6dc6b"
      },
      "source": [
        "### Model configuration\n",
        "\n",
        "You'll start with customizations for the model component within your agent. Refer to the Vertex AI documentation for more information about configuration parameters related to [generative AI model versions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versioning), [safety attributes](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-attributes), and [model parameters](https://ai.google.dev/gemini-api/docs/models/gemini#model-attributes):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "5408d3da2726"
      },
      "outputs": [],
      "source": [
        "## Model variant and version\n",
        "model = \"gemini-2.0-flash\"\n",
        "\n",
        "## Model safety settings\n",
        "from langchain_google_vertexai import HarmBlockThreshold, HarmCategory\n",
        "\n",
        "safety_settings = {\n",
        "    HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,\n",
        "    HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,\n",
        "    HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,\n",
        "    HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,\n",
        "    HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,\n",
        "}\n",
        "\n",
        "## Model parameters\n",
        "model_kwargs = {\n",
        "    \"temperature\": 0.3,\n",
        "    \"max_output_tokens\": 1000,\n",
        "    \"top_p\": 0.95,\n",
        "    \"top_k\": 40,\n",
        "    \"safety_settings\": safety_settings,\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5e48ed43107e"
      },
      "source": [
        "### Agent configuration\n",
        "\n",
        "You can also customize aspects of the agent component, including whether it should return all of the intermediate steps for a given input prompt and output response, maximum number of iterations, how to handle parsing errors, and the size of the sliding context window that the agent has visibility into:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {
        "id": "08623f46a9e4"
      },
      "outputs": [],
      "source": [
        "# Agent parameters\n",
        "agent_executor_kwargs = {\n",
        "    \"return_intermediate_steps\": True,\n",
        "    \"max_iterations\": 3,\n",
        "    \"handle_parsing_errors\": False,\n",
        "    \"trim_intermediate_steps\": -1,\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "164b7a580493"
      },
      "source": [
        "Each component within your agent has additional parameters that can be customized or overridden, including the system instructions, preamble prompts, ability to manage chat sessions and history so that your agent maintains context between multi-turn queries.\n",
        "\n",
        "Each component within your agent (model, tools, reasoning) is modular and composable so that you can customize your agent as little or as much as you want.\n",
        "\n",
        "Refer to the [Agent Engine documentation in Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview) for more details on each agent component and the available options for customization."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6415b2a47a0e"
      },
      "source": [
        "## Cleaning up\n",
        "\n",
        "After you've finished, it's a good practice to clean up your cloud resources. You can delete the deployed Agent Engine instance to avoid any unexpected charges on your Google Cloud account."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {
        "id": "7cec827288b7"
      },
      "outputs": [],
      "source": [
        "remote_agent.delete()"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "intro_agent_engine.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
