{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ur8xi4C7S06n"
      },
      "outputs": [],
      "source": [
        "# Copyright 2025 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": "TykEnWYpmYgd"
      },
      "source": [
        "# Intro to Gemini Enterprise\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/search/gemini-enterprise/intro_gemini_enterprise.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://www.gstatic.com/pantheon/images/bigquery/welcome_page/colab-logo.svg\" alt=\"Google Colaboratory logo\"><br> Open 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%2Fsearch%2Fgemini-enterprise%2Fintro_gemini_enterprise.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://lh3.googleusercontent.com/JmcxdQi-qOpctIvWKgPtrzZdJJK-J3sWE1RsfjZNwshCFgE_9fULcNpuXYTilIR2hjwN\" alt=\"Google Cloud Colab Enterprise logo\"><br> Open in Colab Enterprise\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/search/gemini-enterprise/intro_gemini_enterprise.ipynb\">\n",
        "      <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\"><br> Open in Workbench\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/search/gemini-enterprise/intro_gemini_enterprise.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",
        "</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/search/gemini-enterprise/intro_gemini_enterprise.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/search/gemini-enterprise/intro_gemini_enterprise.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/search/gemini-enterprise/intro_gemini_enterprise.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/search/gemini-enterprise/intro_gemini_enterprise.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/search/gemini-enterprise/intro_gemini_enterprise.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>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q9SSXN56moZJ"
      },
      "source": [
        "| | |\n",
        "|-|-|\n",
        "| Author(s) | [Dave Wang](https://github.com/wadave/), [Holt Skinner](https://github.com/holtskinner/) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JAPoU8Sm5E6e"
      },
      "source": [
        "## Overview\n",
        "\n",
        "[Google Gemini Enterprise](https://cloud.google.com/products/gemini-enterprise) is a powerful AI-powered search and productivity tool designed for businesses. It acts as a central hub for finding information and getting things done within an organization. It unlocks enterprise expertise for employees with agents that bring together Gemini advanced reasoning, Google-quality search, and enterprise data, regardless of where it is hosted.\n",
        "\n",
        "This notebook demonstrates how to use the Gemini Enterprise Client libraries to access the search engine and make `search` and `answer` queries.\n",
        "\n",
        "**Reference:**\n",
        "\n",
        "- https://cloud.google.com/gemini/enterprise/docs/libraries#client-libraries-usage-python\n",
        "- https://cloud.google.com/gemini/enterprise/docs/reference/rest"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i7EUnXsZhAGF"
      },
      "source": [
        "### Install client library\n",
        "\n",
        "Install the following packages required to execute this notebook."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2b4ef9b72d43"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet google-cloud-discoveryengine"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f42d12d15616"
      },
      "source": [
        "### Restart 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 restarts the current kernel.\n",
        "\n",
        "The restart might take a minute or longer. After it's restarted, continue to the next step."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f3d98395d9a4"
      },
      "outputs": [],
      "source": [
        "import IPython\n",
        "\n",
        "app = IPython.Application.instance()\n",
        "app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "89cf56cd5a4d"
      },
      "source": [
        "<div class=\"alert alert-block alert-warning\">\n",
        "<b>⚠️ The kernel is going to restart. Wait until it's finished before continuing to the next step. ⚠️</b>\n",
        "</div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2FyOKZ4aIW5h"
      },
      "source": [
        "### Authenticate your notebook environment (Colab only)\n",
        "\n",
        "If you're running this notebook on Google Colab, run the cell below to authenticate your environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "XXpf9rYGIb60"
      },
      "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": "WReHDGG5g0XY"
      },
      "source": [
        "### Set Google Cloud project information\n",
        "\n",
        "Learn more about [setting up a project and a development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment).\n",
        "\n",
        "**If you don't know your project ID**, try the following:\n",
        "\n",
        "* Run `gcloud config list`.\n",
        "* Run `gcloud projects list`.\n",
        "* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "oM1iC_MfAts1"
      },
      "outputs": [],
      "source": [
        "# Use the environment variable if the user doesn't provide Project ID.\n",
        "import os\n",
        "\n",
        "LOCATION = \"global\"  # @param {type: \"string\"}\n",
        "ENGINE_ID = \"[your-Gemini Enterprise-app-id]\"  # This is from your pre-created Gemini Enterprise app.\n",
        "\n",
        "# fmt: off\n",
        "PROJECT_ID = \"[your-project-id]\"  # @param {type: \"string\", placeholder: \"[your-project-id]\", isTemplate: true}\n",
        "# fmt: on\n",
        "if not PROJECT_ID or PROJECT_ID == \"[your-project-id]\":\n",
        "    PROJECT_ID = str(os.environ.get(\"GOOGLE_CLOUD_PROJECT\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3ec91fa477b9"
      },
      "source": [
        "### Prerequisites\n",
        "\n",
        "- You need to follow [this quickstart guide](https://cloud.google.com/gemini/enterprise/docs/quickstart-gemini-enterprise) to set up datastore and engine first.\n",
        "- Make a note of your Gemini Enterprise engine id (app id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ygUXErJxaSVj"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "63yT2Wg7aWiP"
      },
      "outputs": [],
      "source": [
        "from google.api_core.client_options import ClientOptions\n",
        "from google.cloud import discoveryengine_v1 as discoveryengine\n",
        "from google.protobuf.json_format import MessageToDict"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YjgeLM3KIBEv"
      },
      "source": [
        "## Search method\n",
        "\n",
        "Use the [`search()`](https://cloud.google.com/gemini/enterprise/docs/preview-search-results) method to retrieve all search results for a given query."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "T_EQbaViIBEv"
      },
      "outputs": [],
      "source": [
        "def get_search_sdk_response(\n",
        "    project_id: str,\n",
        "    location: str,\n",
        "    engine_id: str,\n",
        "    search_query: str,\n",
        "    prompt_preamble: str | None = None,\n",
        ") -> list[discoveryengine.SearchResponse]:\n",
        "    \"\"\"Retrieves search results from using the Discovery Engine Python SDK.\n",
        "\n",
        "    Args:\n",
        "        project_id: The Google Cloud project ID.\n",
        "        location: The location of the Discovery Engine (e.g., \"global\", \"us-central1\").\n",
        "        engine_id: The ID of the Discovery Engine.\n",
        "        search_query: The search query string.\n",
        "        prompt_preamble: The preamble to use for search summaries.\n",
        "\n",
        "    Returns:\n",
        "        A list of `discoveryengine.SearchResponse` objects containing the search results.\n",
        "        This list may be empty if no results are found.\n",
        "\n",
        "    \"\"\"\n",
        "    #  For more information, refer to:\n",
        "    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store\n",
        "    client_options = (\n",
        "        ClientOptions(api_endpoint=f\"{location}-discoveryengine.googleapis.com\")\n",
        "        if location != \"global\"\n",
        "        else None\n",
        "    )\n",
        "\n",
        "    # Create a client\n",
        "    client = discoveryengine.SearchServiceClient(client_options=client_options)\n",
        "\n",
        "    # The full resource name of the search app serving config\n",
        "    serving_config = f\"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_config\"\n",
        "\n",
        "    # Optional - only supported for unstructured data: Configuration options for search.\n",
        "    # Refer to the `ContentSearchSpec` reference for all supported fields:\n",
        "    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec\n",
        "    content_search_spec = discoveryengine.SearchRequest.ContentSearchSpec(\n",
        "        # For information about snippets, refer to:\n",
        "        # https://cloud.google.com/generative-ai-app-builder/docs/snippets\n",
        "        snippet_spec=discoveryengine.SearchRequest.ContentSearchSpec.SnippetSpec(\n",
        "            return_snippet=True\n",
        "        ),\n",
        "        # For information about search summaries, refer to:\n",
        "        # https://cloud.google.com/generative-ai-app-builder/docs/get-search-summaries\n",
        "        summary_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec(\n",
        "            summary_result_count=5,\n",
        "            include_citations=True,\n",
        "            ignore_adversarial_query=True,\n",
        "            ignore_non_summary_seeking_query=True,\n",
        "            model_prompt_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec(\n",
        "                preamble=prompt_preamble\n",
        "            ),\n",
        "            model_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec(\n",
        "                version=\"preview\",\n",
        "            ),\n",
        "        ),\n",
        "        # -------extractive content-----\n",
        "        extractive_content_spec=discoveryengine.SearchRequest.ContentSearchSpec.ExtractiveContentSpec(\n",
        "            max_extractive_segment_count=2,\n",
        "            max_extractive_answer_count=2,\n",
        "            return_extractive_segment_score=True,\n",
        "        ),\n",
        "    )\n",
        "\n",
        "    # Refer to the `SearchRequest` reference for all supported fields:\n",
        "    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest\n",
        "    request = discoveryengine.SearchRequest(\n",
        "        serving_config=serving_config,\n",
        "        query=search_query,\n",
        "        page_size=10,\n",
        "        content_search_spec=content_search_spec,\n",
        "        query_expansion_spec=discoveryengine.SearchRequest.QueryExpansionSpec(\n",
        "            condition=discoveryengine.SearchRequest.QueryExpansionSpec.Condition.AUTO,\n",
        "        ),\n",
        "        spell_correction_spec=discoveryengine.SearchRequest.SpellCorrectionSpec(\n",
        "            mode=discoveryengine.SearchRequest.SpellCorrectionSpec.Mode.AUTO\n",
        "        ),\n",
        "    )\n",
        "\n",
        "    response = client.search(request)\n",
        "    return response"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "9bxnz1ZnIBEv"
      },
      "outputs": [],
      "source": [
        "search_query = \"Who founded Cymbal Bank?\"\n",
        "\n",
        "response = get_search_sdk_response(\n",
        "    PROJECT_ID,\n",
        "    LOCATION,\n",
        "    ENGINE_ID,\n",
        "    search_query,\n",
        ")\n",
        "\n",
        "print(response.summary)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "0osSLrWOIBEv"
      },
      "outputs": [],
      "source": [
        "document_dict = MessageToDict(\n",
        "    response.results[0].document._pb, preserving_proto_field_name=True\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "M5Ad5MORIBEv"
      },
      "outputs": [],
      "source": [
        "document_dict[\"derived_struct_data\"][\"extractive_answers\"][0][\"content\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fzxr_0yhIBEv"
      },
      "source": [
        "## Answer method\n",
        "\n",
        "Use the [`answer()`](https://cloud.google.com/gemini/enterprise/docs/answer) method to provide a conversational experience for search results.\n",
        "\n",
        "Key features of the answer method are as follows:\n",
        "\n",
        "  - The ability to generate answers to complex queries. For example, the answer method can break down compound queries, such as the following, into multiple, smaller queries to return better results that are used to power better answers:\n",
        "    - \"What is Google Cloud and Google Ads respective revenue in 2024?\"\n",
        "    - \"After how many years since its founding, did Google reach 1 billion USD revenue?\"\n",
        "  - The ability to combine search and answer generation in a multi-turn conversation by calling the answer method in each turn.\n",
        "  - The ability to pair with the search method to reduce search latency. You can call the search method and the answer method separately and render the search results and answers in different iframes at different times. This means that you can show your users search results (the 10 blue links) within milliseconds. You don't need to wait for answers to be generated before you can show search results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "id": "qzRQ8MYRIBEz"
      },
      "outputs": [],
      "source": [
        "def get_answer_sdk_response(\n",
        "    project_id: str,\n",
        "    location: str,\n",
        "    engine_id: str,\n",
        "    query: str,\n",
        ") -> discoveryengine.AnswerQueryResponse:\n",
        "    \"\"\"Retrieves an answer from the Discovery Engine using the AnswerQuery API.\n",
        "\n",
        "    This function queries the specified Discovery Engine with the provided query\n",
        "    and configuration options using the `AnswerQuery` API. It supports\n",
        "    specifying a location-specific endpoint for the API.\n",
        "\n",
        "    Args:\n",
        "        project_id: The Google Cloud project ID.\n",
        "        location: The location of the Discovery Engine (e.g., \"global\", \"us-central1\").\n",
        "        engine_id: The ID of the Discovery Engine.\n",
        "        query: The query string.\n",
        "\n",
        "    Returns:\n",
        "        A `discoveryengine.AnswerQueryResponse` object containing the answer,\n",
        "        citations, and other related information.\n",
        "\n",
        "    #  For more information, refer to:\n",
        "    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store\n",
        "    \"\"\"\n",
        "    client_options = (\n",
        "        ClientOptions(api_endpoint=f\"{location}-discoveryengine.googleapis.com\")\n",
        "        if location != \"global\"\n",
        "        else None\n",
        "    )\n",
        "\n",
        "    # Create a client\n",
        "    client = discoveryengine.ConversationalSearchServiceClient(\n",
        "        client_options=client_options\n",
        "    )\n",
        "\n",
        "    # The full resource name of the Search serving config\n",
        "    serving_config = f\"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config\"\n",
        "\n",
        "    # Optional: Options for query phase\n",
        "    # The `query_understanding_spec` below includes all available query phase options.\n",
        "    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec\n",
        "    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(\n",
        "        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(\n",
        "            disable=False,  # Optional: Disable query rephraser\n",
        "            max_rephrase_steps=1,  # Optional: Number of rephrase steps\n",
        "        ),\n",
        "        # Optional: Classify query types\n",
        "        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(\n",
        "            types=[\n",
        "                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,\n",
        "                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,\n",
        "            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both\n",
        "        ),\n",
        "    )\n",
        "\n",
        "    # Optional: Options for answer phase\n",
        "    # The `answer_generation_spec` below includes all available query phase options.\n",
        "    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec\n",
        "    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(\n",
        "        ignore_adversarial_query=False,  # Optional: Ignore adversarial query\n",
        "        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query\n",
        "        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant\n",
        "        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(\n",
        "            model_version=\"gemini-2.0-flash/answer_gen/v2\",  # Optional: Model to use for answer generation\n",
        "        ),\n",
        "        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(\n",
        "            preamble=\"Give a detailed answer.\",  # Optional: Natural language instructions for customizing the answer.\n",
        "        ),\n",
        "        include_citations=True,  # Optional: Include citations in the response\n",
        "        answer_language_code=\"en\",  # Optional: Language code of the answer\n",
        "    )\n",
        "\n",
        "    # Initialize request argument(s)\n",
        "    request = discoveryengine.AnswerQueryRequest(\n",
        "        serving_config=serving_config,\n",
        "        query=discoveryengine.Query(text=query),\n",
        "        session=None,  # Optional: include previous session ID to continue a conversation\n",
        "        query_understanding_spec=query_understanding_spec,\n",
        "        answer_generation_spec=answer_generation_spec,\n",
        "    )\n",
        "\n",
        "    # Make the request\n",
        "    response = client.answer_query(request)\n",
        "\n",
        "    return response"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "metadata": {
        "id": "_zwOQEqJIBE0"
      },
      "outputs": [],
      "source": [
        "query = \"Who founded Cymbal Bank?\"\n",
        "response = get_answer_sdk_response(\n",
        "    PROJECT_ID,\n",
        "    LOCATION,\n",
        "    ENGINE_ID,\n",
        "    query,\n",
        ")\n",
        "\n",
        "print(response.answer.answer_text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TpV-iwP9qw9c"
      },
      "source": [
        "## Cleaning up\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "7f14b3b54cb0"
      },
      "outputs": [],
      "source": [
        "# Delete search engine and datastore\n",
        "\n",
        "\n",
        "def delete_search_engine(\n",
        "    project_id: str, location: str, data_store_id: str, search_engine_id: str\n",
        "):\n",
        "    \"\"\"Deletes a Discovery Engine Search Engine.\n",
        "\n",
        "    Args:\n",
        "        project_id: The Google Cloud project ID.\n",
        "        location: The location of the Data Store (e.g., \"global\").\n",
        "        data_store_id: The ID of the Data Store containing the Search Engine.\n",
        "        search_engine_id: The ID of the Search Engine to delete.\n",
        "    \"\"\"\n",
        "    client = discoveryengine.SearchEngineServiceClient()\n",
        "\n",
        "    # Construct the Search Engine name.\n",
        "    search_engine_name = client.search_engine_path(\n",
        "        project=project_id,\n",
        "        location=location,\n",
        "        data_store=data_store_id,\n",
        "        search_engine=search_engine_id,\n",
        "    )\n",
        "\n",
        "    try:\n",
        "        # Delete the Search Engine.\n",
        "        client.delete_search_engine(name=search_engine_name)\n",
        "        print(f\"Search Engine '{search_engine_id}' deleted successfully.\")\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"Error deleting Search Engine: {e}\")\n",
        "\n",
        "\n",
        "data_store_id = \"[your-data-store-id]\"  # Replace with your Data Store ID\n",
        "delete_search_engine(PROJECT_ID, LOCATION, data_store_id, ENGINE_ID)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "intro_gemini_enterprise.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
