{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "copyright"
      },
      "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": "title"
      },
      "source": [
        "# Retail AI Location Strategy: Autonomous Site Selection & Market Analysis\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/use-cases/retail/retail_ai_location_strategy_gemini_3.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/agent-platform/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fgemini%2Fuse-cases%2Fretail%2Fretail_ai_location_strategy_gemini_3.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/agent-platform/workbench/instances?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/use-cases/retail/retail_ai_location_strategy_gemini_3.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://storage.googleapis.com/github-repo/workbench-icon.svg\" alt=\"Workbench 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/gemini/use-cases/retail/retail_ai_location_strategy_gemini_3.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",
        "<p>\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/use-cases/retail/retail_ai_location_strategy_gemini_3.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/use-cases/retail/retail_ai_location_strategy_gemini_3.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/use-cases/retail/retail_ai_location_strategy_gemini_3.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/use-cases/retail/retail_ai_location_strategy_gemini_3.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/use-cases/retail/retail_ai_location_strategy_gemini_3.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",
        "</p>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "authors"
      },
      "source": [
        "| Authors |\n",
        "| --- |\n",
        "| [Deepak Moonat](https://github.com/dmoonat) |\n",
        "| [Lavi Nigam](https://github.com/lavinigam-gcp) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "overview"
      },
      "source": [
        "## Overview\n",
        "\n",
        "**Gemini 3** is Google's latest flagship model family, trained to be especially proficient in:\n",
        "\n",
        "* **Advanced reasoning and complex instruction following**  \n",
        "* **Agentic operations and autonomous code execution**  \n",
        "* **Multimodal understanding across long contexts** (text, image, audio, video)\n",
        "\n",
        "\n",
        "In this notebook, we will explore **Gemini 3**, capable of performing complex market research.\n",
        "\n",
        "### The Business Problem: The \"Synthesis Bottleneck\"\n",
        "Opening a physical retail location (e.g., a café, gym, or boutique) is a high-stakes investment often plagued by a lack of unified data.\n",
        "*   **The Data Fragmentation:** Demographics are on Wikipedia, competitors are on Google Search/Maps, rent trends are in news articles, and math needs to be done in spreadsheets.\n",
        "*   **The Latency:** Validating a single location typically takes an analyst 1-2 weeks of manual research.\n",
        "*   **The Risk:** Decisions are often made on \"gut feeling\" rather than data, leading to a high failure rate for new brick-and-mortar businesses.\n",
        "\n",
        "**The Solution:** An AI pipeline that unifies these disparate data sources into a coherent strategy in minutes, not weeks.\n",
        "\n",
        "### Real-World Scenario\n",
        "Imagine you are the **Chief Strategy Officer** for a retail chain. You have identified a city (e.g., \"Bangalore\"), but you need to know the *exact* micro-market strategy.\n",
        "\n",
        "You need an intelligent assistant that can:\n",
        "1.  **Validate** if the market is growing (requires live web data).\n",
        "2.  **Locate** every competitor on a map (requires Places APIs).\n",
        "3.  **Calculate** saturation density (requires Python code).\n",
        "4.  **Recommend** a specific strategy based on the data (requires reasoning).\n",
        "5.  **Present** the findings to the board (requires coding HTML).\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n",
        "\n",
        "### The Architecture: Why Gemini 3?\n",
        "This notebook demonstrates how to chain five distinct capabilities of Gemini 3 to solve this problem. We aren't just asking the model to \"write text\"; we are asking it to use tools to interact with the real world.\n",
        "\n",
        "| Stage | The Challenge | The Gemini 3 Solution |\n",
        "| :--- | :--- | :--- |\n",
        "| **1. Research** | LLMs have a knowledge cutoff. They don't know today's rent trends. | **Search Grounding:** Allows the model to fetch live, verifiable data from the web. |\n",
        "| **2A. Mapping** | LLMs hallucinate addresses and physical locations. | **Function Calling:** The model autonomously queries the **Google Maps Places API** for ground-truth data. |\n",
        "| **2B. Analysis** | LLMs are poor at complex arithmetic and density calculations. | **Code Execution:** The model writes and runs **Python code** to perform precise data science on the fly. |\n",
        "| **3. Strategy** | Raw data doesn't equal insight. We need \"Executive Reasoning.\" | **Thinking Mode:** Uses extended reasoning to weigh pros/cons and produce structured JSON decisions. |\n",
        "| **4. Reporting** | Text is boring. Stakeholders need visual slides. | **Code Generation:** The model designs a high-fidelity, multi-slide **HTML/CSS report** from scratch. |\n",
        "\n",
        "---\n",
        "\n",
        "### System Flow\n",
        "\n",
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_01.png)\n",
        "\n",
        "\n",
        "---\n",
        "\n",
        "### Learning Objectives\n",
        "\n",
        "By the end of this notebook, you will understand how to architect sophisticated setup using Gemini 3. Specifically, you will learn to:\n",
        "\n",
        "*   **Architect Multi-stage Workflows:** Move beyond single-turn prompts to build a multi-stage pipeline where the model maintains context across research, analysis, and decision-making phases.\n",
        "*   **Orchestrate Multi-Modal Tools:** Apply the integration of **Search Grounding** (for fresh data), **Function Calling** (for Maps interaction), and **Code Execution** (for computation) within a single session.\n",
        "*   **Implement Hybrid Grounding:** Solve the \"hallucination problem\" by forcing the model to base its reasoning on retrieved real-world data (Google Maps) and verified web sources.\n",
        "*   **Leverage Extended Reasoning:** Use Gemini 3's advanced thinking capabilities to produce structured, strategic outputs (JSON) suitable for enterprise downstream applications.\n",
        "*   **Autonomous Asset Generation:** Direct the model to act as a full-stack developer, autonomously generating and styling professional HTML reports to visualize your findings."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "setup-header"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "prerequisites"
      },
      "source": [
        "### Prerequisites\n",
        "\n",
        "**Required:**\n",
        "- Python 3.9 or higher\n",
        "- Google Cloud project with Vertex AI API enabled\n",
        "- Google Maps API key (Places APIs)\n",
        "- Completed [Intro to Gemini 3 Pro](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/getting-started/intro_gemini_3_pro.ipynb) (L100 tutorial)\n",
        "\n",
        "**Helpful:**\n",
        "- Familiarity with Jupyter notebooks\n",
        "- Basic understanding of AI concepts"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install-header"
      },
      "source": [
        "### Installation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "install-packages"
      },
      "outputs": [],
      "source": [
        "# Install required packages\n",
        "%pip install --upgrade --quiet \\\n",
        "    google-genai \\\n",
        "    googlemaps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "auth-header"
      },
      "source": [
        "### Authenticate (Colab Only)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "authenticate"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "# Authenticate if running on Colab\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import auth\n",
        "\n",
        "    auth.authenticate_user()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "project-header"
      },
      "source": [
        "### Set Up Google Cloud Project"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "project-setup"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# Configure your Google Cloud project\n",
        "# fmt: off\n",
        "PROJECT_ID = \"[your-project-id]\"  # @param {type: \"string\", placeholder: \"[your-project-id]\", isTemplate: true}\n",
        "# fmt: on\n",
        "\n",
        "if not PROJECT_ID or PROJECT_ID == \"[your-project-id]\":\n",
        "    PROJECT_ID = str(os.environ.get(\"GOOGLE_CLOUD_PROJECT\"))\n",
        "\n",
        "if not PROJECT_ID:\n",
        "    raise ValueError(\"Please set PROJECT_ID to your Google Cloud project ID\")\n",
        "\n",
        "LOCATION = \"global\"  # Gemini 3 is available globally\n",
        "\n",
        "print(f\"✅ Using project: {PROJECT_ID}\")\n",
        "print(f\"✅ Using location: {LOCATION}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "maps-api-header"
      },
      "source": [
        "### Set Up Google Maps API Key\n",
        "\n",
        "**First, enable the Maps Places API in your Google Cloud Console:**\n",
        "[Maps Places API](https://console.cloud.google.com/apis/api/places-backend.googleapis.com/overview)\n",
        "\n",
        "\n",
        "Once you've enable the relevant Google Maps APIs, you can [generate a Maps API key](https://developers.google.com/maps/documentation/geocoding/get-api-key)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "maps-api-key"
      },
      "outputs": [],
      "source": [
        "# For Colab: Store API key in Colab Secrets\n",
        "# [Left panel, look for a key icon] Secrets → Add MAPS_API_KEY\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import userdata\n",
        "\n",
        "    MAPS_API_KEY = userdata.get(\"MAPS_API_KEY\")\n",
        "else:\n",
        "    # For local/production: Use environment variable\n",
        "    MAPS_API_KEY = os.environ.get(\"MAPS_API_KEY\")\n",
        "\n",
        "if not MAPS_API_KEY:\n",
        "    raise ValueError(\n",
        "        \"Please set MAPS_API_KEY:\\n\"\n",
        "        \"  Colab: Add to Secrets (Settings → Secrets)\\n\"\n",
        "        \"  Local: export MAPS_API_KEY=your_api_key\"\n",
        "    )\n",
        "\n",
        "print(\"✅ Maps API key configured\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "imports-header"
      },
      "source": [
        "### Import Libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "imports"
      },
      "outputs": [],
      "source": [
        "# Standard libraries\n",
        "import datetime\n",
        "import json\n",
        "import os\n",
        "import sys\n",
        "import warnings\n",
        "\n",
        "# Suppress all warnings from the google.genai module\n",
        "warnings.filterwarnings(\"ignore\", module=\"google.genai\")\n",
        "\n",
        "\n",
        "# Display libraries\n",
        "from IPython.display import HTML, Image, Markdown, display\n",
        "\n",
        "# Google Gen AI SDK\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "\n",
        "# For structured output\n",
        "from pydantic import BaseModel\n",
        "\n",
        "print(\"✅ All libraries imported successfully\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "client-header"
      },
      "source": [
        "### Initialize Gemini Client"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "client-init"
      },
      "outputs": [],
      "source": [
        "# Initialize the Gemini client\n",
        "client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)\n",
        "\n",
        "# Set the model\n",
        "MODEL_ID = \"gemini-3.1-pro-preview\"\n",
        "\n",
        "print(\"✅ Gemini client initialized\")\n",
        "print(f\"✅ Using model: {MODEL_ID}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "config-header"
      },
      "source": [
        "## Configure Your Analysis"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "config-set-location"
      },
      "source": [
        "### Set Your Location and Business Type"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "config-code"
      },
      "outputs": [],
      "source": [
        "print(\"=\" * 70)\n",
        "print(\"SMART LOCATION FINDER - CONFIGURATION\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "# Configure your analysis parameters\n",
        "# You can change these to analyze any location worldwide!\n",
        "\n",
        "# Target location (city or area)\n",
        "# Examples:\n",
        "#   - \"Whitefield, Bangalore, India\"\n",
        "#   - \"Austin, Texas, USA\"\n",
        "#   - \"Shibuya, Tokyo, Japan\"\n",
        "#   - \"Shoreditch, London, UK\"\n",
        "TARGET_LOCATION = \"KR Puram, Bangalore, India\"  # @param {type: \"string\"}\n",
        "\n",
        "# Business type you want to open\n",
        "# Examples:\n",
        "#   - \"specialty coffee shop\"\n",
        "#   - \"fitness studio\"\n",
        "#   - \"fast-casual restaurant\"\n",
        "#   - \"bookstore cafe\"\n",
        "BUSINESS_TYPE = \"fitness studio\"  # @param {type: \"string\"}\n",
        "\n",
        "# Display configuration\n",
        "print(f\"\\n📍 Target Location: {TARGET_LOCATION}\")\n",
        "print(f\"🏪 Business Type: {BUSINESS_TYPE}\")\n",
        "\n",
        "print(\"\\n\" + \"=\" * 70)\n",
        "print(\"Configuration complete! Starting analysis...\")\n",
        "print(\"=\" * 70)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "config-note"
      },
      "source": [
        "**Note:** You can change these parameters to analyze any location in the world. The notebook will adapt all prompts and analysis to your specific inputs."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part1-header"
      },
      "source": [
        "## PART 1: Market Research"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G5GiiJFIh1hb"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_02.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part1-goal"
      },
      "source": [
        "### The Goal: \"Macro\" Viability Assessment\n",
        "Referring back to our System Flow, we are starting at the **Data Gathering** phase. Before we zoom into specific streets or buildings, we must validate the **Macro-Economic Environment**.\n",
        "\n",
        "Our first objective is to answer: *\"Is this location economically viable for this specific business type right now?\"*\n",
        "\n",
        "### The Technical Challenge: The Knowledge Cutoff\n",
        "If we asked a standard LLM, *\"What are the commercial rental trends in KR Puram?\"*, it relies on training data that might be 6–12 months old **(Gemini 3 has a knowledge cutoff date of Jan'2025)**. In the fast-moving retail world, old data is dangerous. It might miss:\n",
        "*   A new metro station that opened last month (increasing foot traffic).\n",
        "*   A recent spike in commercial rents.\n",
        "*   New demographic shifts (e.g., a new tech park bringing in young professionals).\n",
        "\n",
        "### The Solution: Gemini 3 with Search Grounding\n",
        "To solve this, we activate **Search Grounding**. This connects the model to Google Search, allowing it to:\n",
        "1.  **Query** live web sources for real-time demographics and news.\n",
        "2.  **Retrieve** current economic indicators.\n",
        "3.  **Synthesize** disparate information (census data + news articles + real estate listings) into a coherent analyst report.\n",
        "\n",
        "**What we will do:**\n",
        "We will construct a prompt that acts as a \"Market Research Analyst,\" specifically requesting data on **Demographics**, **Market Growth**, and **Commercial Viability**. Notice how the system instruction enforces factual, data-driven responses."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "part1-implementation"
      },
      "outputs": [],
      "source": [
        "# get current date\n",
        "CURRENT_DATE = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n",
        "\n",
        "print(\"=\" * 70)\n",
        "print(\"PART 1: MARKET RESEARCH\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "# Define system instruction\n",
        "system_instruction = \"\"\"\n",
        "You are a market research analyst specializing in retail location intelligence.\n",
        "\n",
        "Your task is to research and validate target markets for new business locations.\n",
        "\n",
        "Use Google Search to find:\n",
        "- Current demographics (age, income, population)\n",
        "- Market trends and growth patterns\n",
        "- Industry-specific insights\n",
        "- Commercial real estate trends\n",
        "\n",
        "Provide specific data points with sources. Be factual and data-driven.\n",
        "\"\"\"\n",
        "\n",
        "# Define the research prompt\n",
        "market_research_prompt = f\"\"\"\n",
        "Research {TARGET_LOCATION} as a market for opening a {BUSINESS_TYPE}.\n",
        "\n",
        "Focus on:\n",
        "\n",
        "1. DEMOGRAPHICS:\n",
        "   - Age distribution (identify key age groups)\n",
        "   - Income levels and purchasing power\n",
        "   - Lifestyle indicators (professionals, students, families)\n",
        "   - Population density\n",
        "\n",
        "2. MARKET GROWTH:\n",
        "   - Population trends (growing, stable, declining)\n",
        "   - New residential and commercial developments\n",
        "   - Infrastructure improvements\n",
        "   - Economic growth indicators\n",
        "\n",
        "3. INDUSTRY PRESENCE:\n",
        "   - Existing similar businesses in the area\n",
        "   - Consumer preferences and spending patterns\n",
        "   - Market saturation or opportunity\n",
        "\n",
        "4. COMMERCIAL VIABILITY:\n",
        "   - Foot traffic patterns\n",
        "   - Commercial real estate trends\n",
        "   - Typical rental costs (qualitative: low/medium/high)\n",
        "   - Business environment\n",
        "\n",
        "Provide specific data points (percentages, trends, indicators) with sources.\n",
        "Conclude with: Is this a strong market for {BUSINESS_TYPE}? Why or why not?\n",
        "\n",
        "Current date: {CURRENT_DATE}\n",
        "\"\"\"\n",
        "\n",
        "# Enable Google Search grounding\n",
        "search_tool = types.Tool(google_search=types.GoogleSearch())\n",
        "\n",
        "# Generate market research\n",
        "print(f\"\\n🔍 Researching {TARGET_LOCATION} market for {BUSINESS_TYPE}...\")\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=market_research_prompt,\n",
        "    config=types.GenerateContentConfig(\n",
        "        system_instruction=system_instruction, tools=[search_tool]\n",
        "    ),\n",
        ")\n",
        "\n",
        "# Display the research findings\n",
        "display(Markdown(\"## Market Research Findings\"))\n",
        "display(Markdown(response.text))\n",
        "\n",
        "# Display search sources\n",
        "if response.candidates[0].grounding_metadata:\n",
        "    display(Markdown(\"\\n## Sources\"))\n",
        "    display(\n",
        "        HTML(\n",
        "            response.candidates[\n",
        "                0\n",
        "            ].grounding_metadata.search_entry_point.rendered_content\n",
        "        )\n",
        "    )\n",
        "\n",
        "# Save for later parts\n",
        "market_research_findings = response.text\n",
        "\n",
        "print(\"\\n✅ Market research complete and saved for next parts\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part1-takeaway"
      },
      "source": [
        "### 🔍 Analysis of the Output\n",
        "\n",
        "**What just happened?**\n",
        "The model executed a real-time research task, adeptly connecting unprocessed web information with meaningful strategic understanding.\n",
        "\n",
        "**Key Observations for the Architect:**\n",
        "1.  **Freshness of Data:** Notice the references to current infrastructure (e.g., specific metro lines, new housing developments) or current rental price ranges (e.g., \"₹40 – ₹65 per sq. ft\"). This is data the base model likely did not have in its frozen weights.\n",
        "2.  **Synthesis:** It combined *Demographic Data* (Age/Income) with *Infrastructure Data* (Traffic/Metro) to form a *Business Conclusion* (e.g., \"Avoid the junction, target the residential interior\").\n",
        "3.  **The \"Go/No-Go\" Signal:** The report concludes with a validated \"YES/NO\" on market strength.\n",
        "\n",
        "**Connecting to the Next Step:**\n",
        "We now have the **\"Why\"** (The market is strong because of X, Y, Z).\n",
        "But we still lack the **\"Where\"**.\n",
        "The report might say \"competition is high,\" but it doesn't tell us *exactly* where those competitors are located on a map. To make a strategic decision, we need precise coordinates, not just general trends.\n",
        "\n",
        "This leads us directly to **Part 2A**, where we will switch tools from *Search* to *Maps* to plot the physical battlefield."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part2-header"
      },
      "source": [
        "## PART 2A: Competitor Mapping"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VE2MJEgCj9Rl"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_03.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part2-goal"
      },
      "source": [
        "### The Goal: \"Micro\" Competitive Intelligence\n",
        "In Part 1, we validated that the *macro* market is strong. Now, we zoom in. To open a successful physical business, you need to know exactly who you are fighting against.\n",
        "We need to answer: *\"Where exactly are my competitors located, and are they any good?\"*\n",
        "\n",
        "### The Technical Challenge: The Hallucination Trap\n",
        "If we simply asked an LLM, *\"List all gyms in KR Puram with their addresses,\"* it would likely invent plausible-sounding names (\"KR Puram Fitness Center\") or give outdated addresses.\n",
        "**An LLM is a reasoning engine, not a database.** It does not have a live map of the world in its memory.\n",
        "\n",
        "### The Solution: Function Calling + Google Maps API\n",
        "To get ground-truth data, we use **Function Calling**. This capability allows Gemini 3 to \"realize\" it needs external data and autonomously execute a programming function to get it.\n",
        "\n",
        "**The Architecture:**\n",
        "1.  **We provide a tool:** We give Gemini a Python function (`search_places`) that wraps the Google Maps Places API.\n",
        "2.  **Gemini acts as the agent:** We don't run the function ourselves. We just tell Gemini, \"Find the competitors.\"\n",
        "3.  **Autonomous Execution:** Gemini analyzes the prompt, understands it needs the tool, generates the correct API query (e.g., \"fitness studio in KR Puram\"), executes the call, and interprets the JSON result.\n",
        "\n",
        "**What we will do:**\n",
        "We will first define the `search_places` function. Then, we will prompt Gemini to use this function to build a comprehensive **Competitor Map**, analyzing clustering patterns, quality gaps (ratings), and saturation levels."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part2-step1-header"
      },
      "source": [
        "### Step 1: Define the Search Function"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "part2-step1-code"
      },
      "outputs": [],
      "source": [
        "print(\"=\" * 70)\n",
        "print(\"PART 2: COMPETITOR MAPPING\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "\n",
        "def search_places(query: str):\n",
        "    \"\"\"Search for places using the Google Maps Places API.\"\"\"\n",
        "    import googlemaps\n",
        "\n",
        "    gmaps = googlemaps.Client(key=MAPS_API_KEY)\n",
        "    return gmaps.places(query)\n",
        "\n",
        "\n",
        "# Test the function\n",
        "print(f\"\\n🧪 Testing search function for {BUSINESS_TYPE} near {TARGET_LOCATION}...\")\n",
        "test_query = f\"{BUSINESS_TYPE} near {TARGET_LOCATION}\"\n",
        "test_result = search_places(query=test_query)\n",
        "print(f\"✅ Function works! Found {len(test_result.get('results', []))} results\")\n",
        "if test_result.get(\"results\"):\n",
        "    print(f\"   Sample: {test_result['results'][0]['name']}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part2-step2-header"
      },
      "source": [
        "### Step 2: Use Function Calling with Gemini"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q_VPLsCJxupg"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_06.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "O0syu5aDqSoe"
      },
      "outputs": [],
      "source": [
        "# Define system instruction for competitive analysis\n",
        "system_instruction = \"\"\"\n",
        "You are a market intelligence analyst specializing in competitive landscape analysis.\n",
        "\n",
        "You have access to the search_places() function which uses Google Maps to find competing businesses in a specific area.\n",
        "\n",
        "When analyzing competition:\n",
        "1. Use the function to get REAL data about existing competitors\n",
        "2. Analyze the distribution (clustered vs spread out)\n",
        "3. Identify patterns in location types (malls, main roads, residential areas)\n",
        "4. Note gaps or underserved areas\n",
        "5. Assess market saturation\n",
        "\n",
        "Be specific with the data you receive. Reference actual business names, locations, and ratings.\n",
        "\"\"\"\n",
        "\n",
        "# Prompt for competitor analysis\n",
        "competitor_prompt = f\"\"\"\n",
        "Find all competitors for a {BUSINESS_TYPE} in {TARGET_LOCATION}.\n",
        "\n",
        "Use the search_places function to get real data from Google Maps.\n",
        "\n",
        "After getting the results:\n",
        "1. List the competitors found (name, location, rating)\n",
        "2. Identify any patterns:\n",
        "   - Are they clustered in specific areas/zones?\n",
        "   - What types of locations (shopping areas, main roads, residential)?\n",
        "3. Categorize them if applicable:\n",
        "   - Premium vs budget\n",
        "   - High-rated (4.5+) vs others\n",
        "   - Chain vs independent\n",
        "4. Initial assessment:\n",
        "   - Which areas seem saturated?\n",
        "   - Which areas might be underserved?\n",
        "\n",
        "Be specific and reference the actual data you receive.\n",
        "\n",
        "Current date: {CURRENT_DATE}\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Generate content with function calling enabled\n",
        "print(f\"\\n🗺️ Mapping competitors in {TARGET_LOCATION} using Maps Places API...\")\n",
        "\n",
        "# Send the prompt - model will automatically call the function\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=competitor_prompt,\n",
        "    config=types.GenerateContentConfig(\n",
        "        system_instruction=system_instruction, tools=[search_places]\n",
        "    ),\n",
        ")\n",
        "\n",
        "# Display the analysis\n",
        "display(Markdown(\"## Competitor Analysis\"))\n",
        "display(Markdown(response.text))\n",
        "\n",
        "# Show what function was called\n",
        "print(\"\\n📋 Function Call Details:\")\n",
        "for turn in response.automatic_function_calling_history:\n",
        "    for part in turn.parts:\n",
        "        if part.function_call:\n",
        "            print(f\"   Called: {part.function_call.name}\")\n",
        "            print(f\"   Arguments: {part.function_call.args}\")\n",
        "\n",
        "# Save for later parts\n",
        "competitor_analysis = response.text\n",
        "\n",
        "print(\"\\n✅ Competitor mapping complete and saved for next parts\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "welzwsnwGals"
      },
      "source": [
        "### Recommended\n",
        "\n",
        "- Use `Grounding with Google Maps`, to ground your model's responses, enabling your AI applications to provide local data and geospatial context.\n",
        "- Wrap the Google Maps as a tool, and provide it as a model config\n",
        "- Check out the [documentation](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps) for more details"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ti5Fi8lPGsHW"
      },
      "source": [
        "```\n",
        "# Enable Google Maps grounding\n",
        "maps_tool = types.Tool(google_maps=types.GoogleMaps())\n",
        "```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "USqJlmmaKUqN"
      },
      "source": [
        "**Note:** Use built-in Grounding with Google Maps for simple, conversational applications where you want to automatically add location awareness with minimal code ( source). Use Custom Tools for complex, agentic workflows that require precise control and structured data to pass between different analysis steps. So depending on the use-case one can make a choice."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part2-takeaway"
      },
      "source": [
        "### 🗺️ Analysis of the Output\n",
        "\n",
        "**What just happened?**\n",
        "This was a demonstration of **Automatic Function Calling**.\n",
        "\n",
        "1. **Autonomous Tool Use:** Look at the Function Call Details at the bottom of the output. You didn't have to write the specific query for the tool. The model generated the necessary arguments (e.g., combining the business type and location) dynamically based on your high-level instruction.\n",
        "2.  **Real-World Data:** The list of competitors and their details (e.g., names, ratings) represents real-world businesses with verifiable data. This is not just generated text; it is structured data retrieved from a reliable external source.\n",
        "3.  **Strategic Clustering:** The model didn't just provide a simple list; it analyzed geographical patterns in the data. It can identify and label different zones, such as 'Primary Clusters' where competition is dense, and 'Emerging Clusters' where there might be an opportunity. This requires **spatial reasoning capability**.\n",
        "\n",
        "**Connecting to the Next Step:**\n",
        "We now have two critical pieces of the puzzle:\n",
        "1.  **Market Context (Part 1):** The area is growing and needs premium services.\n",
        "2.  **Competitor Map (Part 2A):** The main roads are saturated, but quality gaps exist.\n",
        "\n",
        "However, \"saturation\" is currently just a *feeling* based on looking at a list. To make a multimillion-dollar investment decision, we need **Math**, not feelings. We need to calculate density scores and quantify the opportunity.\n",
        "Gemini is great at words, but can it do data science?\n",
        "In **Part 2B**, we will hand these datasets to a **Code Execution** engine to perform rigorous gap analysis."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part3-header"
      },
      "source": [
        "## PART 2B: Gap Analysis with Code Execution"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kxlemPB7leos"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_03.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part3-goal"
      },
      "source": [
        "### The Goal: Quantitative \"White Space\" Analysis\n",
        "We have a validated market (Part 1) and a list of competitors (Part 2A). A human analyst would now open Excel to calculate density, saturation, and projected revenue.\n",
        "We need to answer: *\"Which specific zone offers the highest reward for the lowest risk?\"*\n",
        "\n",
        "### The Technical Challenge: The \"Math\" Problem\n",
        "Large Language Models (LLMs) are designed for language, not logic. If you ask an LLM to \"calculate the saturation index of 5 zones based on weighted averages,\" it might give you a plausible-looking number that is mathematically wrong.\n",
        "**For business strategy, we cannot afford \"hallucinated math.\"**\n",
        "\n",
        "### The Solution: Code Execution (Python)\n",
        "Gemini 3 overcomes this by writing and executing **real Python code**. It doesn't guess the answer; it *computes* it.\n",
        "\n",
        "**The Architecture:**\n",
        "1.  **Data Ingestion:** We feed the unstructured text from Part 1 and Part 2B into the prompt.\n",
        "2.  **Code Generation:** Gemini writes a Python script using `pandas` and `numpy`. It structures the data into a DataFrame.\n",
        "3.  **Algorithmic Logic:** It implements complex custom metrics:\n",
        "    *   **Saturation Index:** `(Competitors × Quality Score) / Demand Signal`\n",
        "    *   **Viability Score:** A weighted ranking of all zones.\n",
        "4.  **Execution:** The code runs in a secure sandbox, and the *actual* output (the calculated table) is returned.\n",
        "\n",
        "**What we will do:**\n",
        "We will instruct Gemini to act as a Data Scientist. It will parse our previous findings, define zones, assign scores, and calculate a \"Viability Matrix\" to objectively rank the best locations."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m25syGnsyk4j"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_07.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "part3-implementation"
      },
      "outputs": [],
      "source": [
        "print(\"=\" * 70)\n",
        "print(\"PART 2B: GAP ANALYSIS\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "# Enhanced prompt with context from Parts 1 & 2\n",
        "gap_analysis_prompt = f\"\"\"\n",
        "You have conducted comprehensive research. Here is the COMPLETE CONTEXT:\n",
        "\n",
        "**MARKET RESEARCH FINDINGS (Part 1):**\n",
        "{market_research_findings}\n",
        "\n",
        "**COMPETITOR ANALYSIS (Part 2):**\n",
        "{competitor_analysis}\n",
        "\n",
        "Based on this REAL data for {BUSINESS_TYPE} in {TARGET_LOCATION}, perform an ADVANCED gap analysis.\n",
        "\n",
        "Write Python code to:\n",
        "\n",
        "1. PARSE REAL COMPETITOR DATA FROM PART 2:\n",
        "   Extract ALL competitors mentioned with their:\n",
        "   - Names\n",
        "   - Zones/locations\n",
        "   - Ratings\n",
        "   - Type (Chain/Boutique/Quick-Service based on description)\n",
        "\n",
        "2. EXTRACT MARKET FUNDAMENTALS FROM PART 1:\n",
        "   - Total population\n",
        "   - Population density\n",
        "   - Average income level\n",
        "   - Rental cost tier (High/Medium/Low)\n",
        "   - Key infrastructure (Metro stations, malls, tech parks mentioned)\n",
        "   - Foot traffic patterns\n",
        "\n",
        "3. CALCULATE ADVANCED METRICS PER ZONE:\n",
        "   a) Basic metrics:\n",
        "      - Competitor count\n",
        "      - Competitor density (per sq km)\n",
        "      - Average competitor rating\n",
        "\n",
        "   b) Quality metrics:\n",
        "      - Competition Quality Score: Weight competitors by rating (4.5+ rated = higher threat)\n",
        "      - Chain Dominance Ratio: Percentage of big chains (Starbucks, Third Wave, etc.)\n",
        "      - High-Performer Count: Competitors rated 4.5+\n",
        "\n",
        "   c) Market opportunity metrics:\n",
        "      - Demand Signal: Score based on population density, income, infrastructure from Part 1\n",
        "      - Market Saturation Index: (Competitors × Quality Score) / Demand Signal\n",
        "      - Cost Tier: Estimated rental cost tier (High/Medium/Low based on Part 1)\n",
        "\n",
        "   d) Strategic scores:\n",
        "      - Infrastructure Score: Proximity to Metro/malls/tech parks mentioned in Part 1\n",
        "      - Customer Stickiness: Residential zones (repeat customers) vs Transit zones\n",
        "      - First-Mover Advantage: New infrastructure with low competition\n",
        "\n",
        "4. CATEGORIZE ZONES WITH STRATEGIC INSIGHT:\n",
        "   Not just SATURATED/MODERATE/OPPORTUNITY, but also:\n",
        "   - Opportunity TYPE: \"Underserved Premium\", \"Metro First-Mover\", \"Residential Sticky\", \"Weekend Destination\"\n",
        "   - Risk Level: Based on competition quality and chain dominance (Low/Medium/High)\n",
        "   - Investment Tier: Based on rental costs from Part 1 (High/Medium/Low)\n",
        "   - Best Customer Segment: Weekday corporate, weekend residential, WFH crowd, etc.\n",
        "\n",
        "5. RANK TOP 3 ZONES:\n",
        "   Use multi-factor scoring:\n",
        "   - Low competition density\n",
        "   - Low market saturation\n",
        "   - High demand signals (income, population, foot traffic)\n",
        "   - Strategic advantages (Metro proximity, low chain dominance)\n",
        "   - Manageable costs\n",
        "\n",
        "6. CREATE COMPREHENSIVE TABLE:\n",
        "   Show all zones with: competitors, density, quality score, saturation index,\n",
        "   opportunity type, risk level, investment tier, recommended customer segment\n",
        "\n",
        "Execute the code and provide ACTIONABLE, STRATEGIC recommendations.\n",
        "Be specific about WHY each zone is an opportunity or risk.\n",
        "\n",
        "Current date: {CURRENT_DATE}\n",
        "\"\"\"\n",
        "\n",
        "# Add code execution tool\n",
        "code_execution_tool = types.Tool(code_execution=types.ToolCodeExecution())\n",
        "\n",
        "# Generate analysis with code execution\n",
        "print(\n",
        "    f\"\\n📊 Analyzing competitor density and market opportunities in {TARGET_LOCATION}...\"\n",
        ")\n",
        "print(\"   Using real data from Parts 1 & 2 for comprehensive analysis...\")\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=gap_analysis_prompt,\n",
        "    config=types.GenerateContentConfig(tools=[code_execution_tool]),\n",
        ")\n",
        "\n",
        "# Display the analysis\n",
        "display(Markdown(\"## Gap Analysis\"))\n",
        "display(Markdown(response.text))\n",
        "\n",
        "# Display generated code if available\n",
        "if response.executable_code:\n",
        "    display(Markdown(\"\\n### Generated Python Code\"))\n",
        "    display(Markdown(f\"```python\\n{response.executable_code}\\n```\"))\n",
        "\n",
        "    display(Markdown(\"\\n### Code Output\"))\n",
        "    display(Markdown(f\"```\\n{response.code_execution_result}\\n```\"))\n",
        "\n",
        "# Save for Part 4\n",
        "gap_analysis = response.text\n",
        "\n",
        "print(\"\\n✅ Gap analysis complete and saved for final recommendation\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part3-takeaway"
      },
      "source": [
        "### 📊 Analysis of the Output\n",
        "\n",
        "**What just happened?**\n",
        "This is the most powerful demonstration of **Neuro-Symbolic AI** (combining neural networks with symbolic logic/code).\n",
        "\n",
        "**Key Observations:**\n",
        "1.  **Structured Thinking:** Look at the **Strategic Zone Ranking Table** in the output. Gemini autonomously created columns for *Risk Level*, *Investment Tier*, and *Viability Score*. It didn't just list zones; it created a quantitative model to evaluate and compare them.\n",
        "2.  The \"Blue Ocean\" Finding: This analysis can uncover \"Blue Ocean\" opportunities—areas with high demand but low competition. The generated Python code can identify a top-ranked zone by finding a high 'Demand' score coupled with a low number of 'Competitors'. In contrast, it can also identify high-risk \"Red Ocean\" zones where, despite high demand, the market is oversaturated.\n",
        "3.  **Algorithmic Reasoning:** The model demonstrates algorithmic reasoning by writing Python logic to handle specific edge cases (e.g., correctly calculating saturation if there are zero competitors). This level of conditional logic and mathematical precision is difficult to achieve with pure text-based prompting but is handled reliably by the Code Execution tool.\n",
        "\n",
        "**Connecting to the Next Step:**\n",
        "We now have the Numbers: The analysis identifies the best location mathematically. But business decisions aren't made on numbers alone; they require Nuance.\n",
        "\n",
        "The next logical step is to explore the qualitative aspects of the top-ranked location, such as:\n",
        "\n",
        "\"What is the specific customer persona for this area?\"\n",
        "\"What are the specific risks of opening a business here?\"\n",
        "\"What is a viable mitigation strategy for those risks?\"\n",
        "\n",
        "We need to synthesize these cold, hard numbers into a persuasive **Strategic Narrative**.\n",
        "In **Part 3**, we will switch from \"Calculator Mode\" (Code Execution) to \"Deep Thinking Mode\" (Extended Reasoning) to build the final business case."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-header"
      },
      "source": [
        "## PART 3: Final Recommendation with Extended Reasoning"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nkPK7wnnmZMy"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_04.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-goal"
      },
      "source": [
        "### The Goal: The \"CEO Moment\"\n",
        "We have gathered intelligence (Part 1), mapped the battlefield (Part 2A), and crunched the numbers (Part 2B).\n",
        "Now, we must answer the ultimate question: **\"So, what is the single best move?\"**\n",
        "\n",
        "This is not about listing facts anymore. It is about **Strategic Synthesis**. We need an AI that can weigh conflicting evidence (e.g., \"High demand but high rent\" vs. \"Low rent but low visibility\") and make a definitive, justified recommendation.\n",
        "\n",
        "### The Technical Challenge: Complexity & consistency\n",
        "1.  **Hallucination Risk:** In complex reasoning tasks, models often \"forget\" the specific numbers calculated earlier (e.g., recommending a zone that Part 2 proved was saturated).\n",
        "2.  **Downstream Automation:** We need the output to be computer-readable (JSON) so we can generate a website in Part 4. Generating code directly from large blocks of unorganized text is not feasible.\n",
        "\n",
        "### The Solution: Extended Reasoning & Structured Output\n",
        "We leverage two flagship capabilities of Gemini 3:\n",
        "1.  **Extended Reasoning (Thinking Mode):** We enable `thinking_level=\"HIGH\"`. This forces the model to pause and \"think\" (generate an internal chain-of-thought) before answering. It critiques its own logic, checks against the Part 3 math, and formulates a robust argument.\n",
        "2.  **Structured Output (Pydantic):** We define a strict Python schema (`LocationIntelligenceReport`). The model *must* return data that perfectly matches this structure, ensuring reliable JSON for the next steps.\n",
        "\n",
        "**What we will do:**\n",
        "1.  **Define the Schema:** Create complex Pydantic classes to model our ideal report.\n",
        "2.  **Synthesize:** Feed *all* previous data (Parts 1-2) into the model.\n",
        "3.  **Reason & Decide:** Watch the model \"think\" through the options and output a final, structured strategic plan."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B1xy4npcTJ5q"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_08.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-step1-header"
      },
      "source": [
        "### Step 1: Define the Output Structure (Schema)\n",
        "To ensure our AI consultant produces a report we can *use* programmatically, we define a \"Contract\" using **Pydantic**.\n",
        "*   Instead of saying \"Give me a report,\" we say \"Fill out this exact form.\"\n",
        "*   This ensures we get specific fields like `overall_score` (integer), `chain_dominance_pct` (float), and `next_steps` (list of strings)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "part4-step1-code"
      },
      "outputs": [],
      "source": [
        "print(\"=\" * 70)\n",
        "print(\"PART 3: FINAL RECOMMENDATION\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "# Define structured output schemas with nested complexity\n",
        "\n",
        "\n",
        "class StrengthAnalysis(BaseModel):\n",
        "    \"\"\"Detailed strength with evidence.\"\"\"\n",
        "\n",
        "    factor: str\n",
        "    description: str\n",
        "    evidence_from_analysis: str\n",
        "\n",
        "\n",
        "class ConcernAnalysis(BaseModel):\n",
        "    \"\"\"Detailed concern with mitigation.\"\"\"\n",
        "\n",
        "    risk: str\n",
        "    description: str\n",
        "    mitigation_strategy: str\n",
        "\n",
        "\n",
        "class CompetitionProfile(BaseModel):\n",
        "    \"\"\"Competition characteristics in the zone.\"\"\"\n",
        "\n",
        "    total_competitors: int\n",
        "    density_per_km2: float\n",
        "    chain_dominance_pct: float\n",
        "    avg_competitor_rating: float\n",
        "    high_performers_count: int\n",
        "\n",
        "\n",
        "class MarketCharacteristics(BaseModel):\n",
        "    \"\"\"Market fundamentals for the zone.\"\"\"\n",
        "\n",
        "    population_density: str\n",
        "    income_level: str\n",
        "    infrastructure_access: str\n",
        "    foot_traffic_pattern: str\n",
        "    rental_cost_tier: str\n",
        "\n",
        "\n",
        "class LocationRecommendation(BaseModel):\n",
        "    \"\"\"Complete recommendation for a specific location.\"\"\"\n",
        "\n",
        "    location_name: str\n",
        "    area: str\n",
        "    overall_score: int\n",
        "    opportunity_type: str\n",
        "    strengths: list[StrengthAnalysis]\n",
        "    concerns: list[ConcernAnalysis]\n",
        "    competition: CompetitionProfile\n",
        "    market: MarketCharacteristics\n",
        "    best_customer_segment: str\n",
        "    estimated_foot_traffic: str\n",
        "    next_steps: list[str]\n",
        "\n",
        "\n",
        "class AlternativeLocation(BaseModel):\n",
        "    \"\"\"Brief summary of alternative location.\"\"\"\n",
        "\n",
        "    location_name: str\n",
        "    area: str\n",
        "    overall_score: int\n",
        "    opportunity_type: str\n",
        "    key_strength: str\n",
        "    key_concern: str\n",
        "    why_not_top: str\n",
        "\n",
        "\n",
        "class LocationIntelligenceReport(BaseModel):\n",
        "    \"\"\"Complete location intelligence analysis report.\"\"\"\n",
        "\n",
        "    target_location: str\n",
        "    business_type: str\n",
        "    analysis_date: str\n",
        "    market_validation: str\n",
        "    total_competitors_found: int\n",
        "    zones_analyzed: int\n",
        "    top_recommendation: LocationRecommendation\n",
        "    alternative_locations: list[AlternativeLocation]\n",
        "    key_insights: list[str]\n",
        "    methodology_summary: str\n",
        "\n",
        "\n",
        "print(\"✅ Complex nested Pydantic schemas defined\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-step2-header"
      },
      "source": [
        "### Step 2: Generate with Deep Reasoning\n",
        "Now we invoke Gemini 3. Notice the configuration:\n",
        "*   `thinking_level=types.ThinkingLevel.HIGH`: Activates the extended reasoning engine.\n",
        "*   `response_schema=LocationIntelligenceReport`: Enforces the Pydantic structure defined above.\n",
        "\n",
        "**Watch the \"Internal Reasoning\":**\n",
        "When the output appears, look for the **🧠 Internal Reasoning** section. You will see the thinking logic."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "part4-step2-code"
      },
      "outputs": [],
      "source": [
        "# Final synthesis prompt with all context\n",
        "final_recommendation_prompt = f\"\"\"\n",
        "Create a comprehensive location intelligence report for opening a {BUSINESS_TYPE} in {TARGET_LOCATION}.\n",
        "\n",
        "SYNTHESIZE ALL DATA FROM PREVIOUS ANALYSIS:\n",
        "\n",
        "**PART 1 - MARKET RESEARCH:**\n",
        "{market_research_findings}\n",
        "\n",
        "**PART 2 - COMPETITOR MAPPING:**\n",
        "{competitor_analysis}\n",
        "\n",
        "**PART 3 - GAP ANALYSIS:**\n",
        "{gap_analysis}\n",
        "\n",
        "TASK:\n",
        "\n",
        "Analyze ALL the data above and provide a complete recommendation with:\n",
        "\n",
        "1. TOP RECOMMENDATION:\n",
        "   - Identify the SINGLE BEST location/zone\n",
        "   - Score it 0-100 based on comprehensive analysis\n",
        "   - Classify opportunity type (e.g., \"Metro First-Mover\", \"Residential Sticky\", \"Underserved Premium\")\n",
        "   - Provide 3-4 detailed STRENGTHS with specific evidence from the analysis\n",
        "   - Provide 2-3 CONCERNS with mitigation strategies\n",
        "   - Detailed competition profile (density, chain dominance, ratings)\n",
        "   - Market characteristics (population, income, infrastructure, traffic, rent)\n",
        "   - Best customer segment to target\n",
        "   - Foot traffic estimate\n",
        "   - 3-5 actionable next steps\n",
        "\n",
        "2. TWO ALTERNATIVE LOCATIONS:\n",
        "   - Second and third best options\n",
        "   - Score each 0-100\n",
        "   - Opportunity type for each\n",
        "   - Key strength and concern for each\n",
        "   - Explain WHY each is NOT the top choice\n",
        "\n",
        "3. KEY INSIGHTS:\n",
        "   - 3-5 high-level strategic insights from the entire analysis\n",
        "\n",
        "4. METHODOLOGY:\n",
        "   - Brief summary of how this analysis was performed\n",
        "\n",
        "Focus on:\n",
        "- Optimal balance of low competition and strong market fundamentals\n",
        "- Clear competitive advantage potential\n",
        "- Sustainable business viability\n",
        "- Risk-adjusted opportunity assessment\n",
        "\n",
        "Be SPECIFIC. Reference actual data from the analysis. Show your reasoning.\n",
        "Return the complete report in structured JSON format matching the schema.\n",
        "\n",
        "Current date: {CURRENT_DATE}\n",
        "\"\"\"\n",
        "\n",
        "# Enable extended reasoning with HIGH thinking level\n",
        "print(\n",
        "    f\"\\n🧠 Generating final recommendation for {BUSINESS_TYPE} in {TARGET_LOCATION}...\"\n",
        ")\n",
        "print(\"   Using DEEP REASONING mode for comprehensive analysis...\")\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=final_recommendation_prompt,\n",
        "    config=types.GenerateContentConfig(\n",
        "        thinking_config=types.ThinkingConfig(\n",
        "            thinking_level=types.ThinkingLevel.HIGH,  # Deep reasoning\n",
        "            include_thoughts=True,  # Show thought process\n",
        "        ),\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=LocationIntelligenceReport,\n",
        "    ),\n",
        ")\n",
        "\n",
        "# Display the reasoning process\n",
        "print(\"\\n\" + \"=\" * 70)\n",
        "print(\"MODEL'S REASONING PROCESS\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "for part in response.candidates[0].content.parts:\n",
        "    if part.thought:\n",
        "        display(Markdown(\"### 🧠 Internal Reasoning\"))\n",
        "        display(Markdown(part.text))\n",
        "        print(\"\\n\" + \"=\" * 70)\n",
        "\n",
        "# Parse the structured output\n",
        "report = response.parsed\n",
        "\n",
        "print(\"\\n\" + \"=\" * 70)\n",
        "print(\"FINAL RECOMMENDATION\")\n",
        "print(\"=\" * 70)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-step3-header"
      },
      "source": [
        "### Step 3: The Strategic Decision\n",
        "Below is the parsed result. Notice how the raw JSON has been rendered into a clean, human-readable format.\n",
        "\n",
        "**Key Output Features:**\n",
        "*   **Top Recommendation:** A single, definitive choice with a calculated score.\n",
        "*   **Evidence-Based:** Every strength cites specific data from previous parts.\n",
        "*   **Actionable:** It doesn't just analyze; it prescribes."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GZIupAwBCQc9"
      },
      "outputs": [],
      "source": [
        "comp = report.top_recommendation.competition\n",
        "market = report.top_recommendation.market\n",
        "\n",
        "strengths_md = \"\"\n",
        "for i, strength in enumerate(report.top_recommendation.strengths, 1):\n",
        "    strengths_md += f\"\"\"**{i}. {strength.factor}**\n",
        "   - {strength.description}\n",
        "   - *Evidence:* {strength.evidence_from_analysis}\\n\n",
        "\"\"\"\n",
        "\n",
        "concerns_md = \"\"\n",
        "for i, concern in enumerate(report.top_recommendation.concerns, 1):\n",
        "    concerns_md += f\"\"\"**{i}. {concern.risk}**\n",
        "   - {concern.description}\n",
        "   - *Mitigation:* {concern.mitigation_strategy}\\n\n",
        "\"\"\"\n",
        "\n",
        "alternatives_md = \"\"\n",
        "for alt in report.alternative_locations:\n",
        "    alternatives_md += f\"\"\"\n",
        "### {alt.location_name} ({alt.area})\n",
        "- **Score:** {alt.overall_score}/100\n",
        "- **Type:** {alt.opportunity_type}\n",
        "- **Strength:** {alt.key_strength}\n",
        "- **Concern:** {alt.key_concern}\n",
        "- **Why Not Top:** {alt.why_not_top}\n",
        "\"\"\"\n",
        "\n",
        "next_steps_md = \"\"\n",
        "for i, step in enumerate(report.top_recommendation.next_steps, 1):\n",
        "    next_steps_md += f\"{i}. {step}\\n\"\n",
        "\n",
        "key_insights_md = \"\"\n",
        "for insight in report.key_insights:\n",
        "    key_insights_md += f\"- {insight}\\n\"\n",
        "\n",
        "markdown_content = f\"\"\"\n",
        "## Executive Summary\n",
        "**Location:** {report.target_location}\n",
        "**Business:** {report.business_type}\n",
        "**Analysis Date:** {report.analysis_date}\n",
        "\n",
        "**Market Validation:** {report.market_validation}\n",
        "**Analysis Scope:** {report.total_competitors_found} competitors analyzed across {report.zones_analyzed} zones\n",
        "\n",
        "## 🏆 Top Recommendation\n",
        "### {report.top_recommendation.location_name}\n",
        "**Area:** {report.top_recommendation.area}\n",
        "**Overall Score:** {report.top_recommendation.overall_score}/100\n",
        "**Opportunity Type:** {report.top_recommendation.opportunity_type}\n",
        "**Target Segment:** {report.top_recommendation.best_customer_segment}\n",
        "\n",
        "#### Strengths:\n",
        "{strengths_md}\n",
        "#### Concerns:\n",
        "{concerns_md}\n",
        "#### Competition Profile:\n",
        "- **Total Competitors:** {comp.total_competitors}\n",
        "- **Density:** {comp.density_per_km2:.2f} competitors/km²\n",
        "- **Chain Dominance:** {comp.chain_dominance_pct:.1f}%\n",
        "- **Avg Rating:** {comp.avg_competitor_rating:.2f} ⭐\n",
        "- **High Performers (4.5+):** {comp.high_performers_count}\n",
        "\n",
        "#### Market Characteristics:\n",
        "- **Population Density:** {market.population_density}\n",
        "- **Income Level:** {market.income_level}\n",
        "- **Infrastructure:** {market.infrastructure_access}\n",
        "- **Foot Traffic:** {market.foot_traffic_pattern}\n",
        "- **Rental Costs:** {market.rental_cost_tier}\n",
        "\n",
        "**Estimated Foot Traffic:** {report.top_recommendation.estimated_foot_traffic}\n",
        "\n",
        "## Alternative Locations\n",
        "{alternatives_md}\n",
        "\n",
        "## 🎯 Next Steps\n",
        "{next_steps_md}\n",
        "\n",
        "## 💡 Key Insights\n",
        "{key_insights_md}\n",
        "\n",
        "## Methodology\n",
        "{report.methodology_summary}\n",
        "\"\"\"\n",
        "\n",
        "# Display the entire report in one go\n",
        "display(Markdown(markdown_content))\n",
        "\n",
        "# Save as JSON\n",
        "with open(\"location_intelligence_report.json\", \"w\") as f:\n",
        "    json.dump(report.model_dump(), f, indent=2)\n",
        "\n",
        "print(\"\\n✅ Report saved to location_intelligence_report.json\")\n",
        "print(\"✅ Final recommendation complete\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "part4-takeaway"
      },
      "source": [
        "### 🧠 Analysis of the Reasoning\n",
        "\n",
        "**What just happened?**\n",
        "The model successfully synthesized qualitative *Market Trends* (from Part 1), geospatial *Competitor Locations* (from Part 2A), and quantitative *Saturation Metrics* (from Part 2B) into a cohesive business strategy.\n",
        "\n",
        "**The \"Aha!\" Moment: The Power of Synthesis**\n",
        "\n",
        "This is where the model connects all the dots from the previous steps. For example, it might connect:\n",
        "\n",
        "- A demographic trend from **Part 1** (e.g., a growing population of young professionals in a specific area).\n",
        "- A geographical gap from **Part 2A** (e.g., a lack of a certain type of business in that same neighborhood).\n",
        "- A quantitative opportunity from **Part 2B** (e.g., a low market saturation score calculated for that area).\n",
        "- **Part 3 (Here)** then synthesizes these individual data points into a single, actionable recommendation (e.g., \"Open a premium version of the business in that neighborhood to cater to the underserved young professional demographic\").\n",
        "\n",
        "This is **Strategic Intelligence** in action. The model doesn't just summarize the data; it identifies a market gap that a human analyst might have missed while looking at disconnected spreadsheets and reports.\n",
        "\n",
        "**Connecting to the Final Step:**\n",
        "We now have the *Strategy* in a structured JSON format. But a JSON file isn't something you present to a Board of Directors. They want a **Presentation/Slide Deck**.\n",
        "In the final section (**Part 4**), we will ask Gemini to act as a \"Frontend Developer\" and autonomously convert this JSON data into a stunning, interactive HTML presentation."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "25a2ee9b"
      },
      "source": [
        "## PART 4: Executive Report Generation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RJSffc9nuwZz"
      },
      "source": [
        "![](https://storage.googleapis.com/github-repo/generative-ai/gemini3/assets/location_finder_05.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f4ab911f"
      },
      "source": [
        "### The Goal: From \"Raw Data\" to \"Client Deliverable\"\n",
        "We have successfully identified the perfect location (*Seegehalli*) and backed it up with math and strategy. But a JSON file is not a deliverable. You cannot present a JSON object to a Board of Directors or an Investor.\n",
        "We need a **Professional Slide Deck**.\n",
        "\n",
        "### The Technical Challenge: The \"Last Mile\" Problem\n",
        "Typically, turning data into a presentation is a manual, tedious process:\n",
        "1.  Copy-paste data from Excel to PowerPoint.\n",
        "2.  Manually adjust fonts, colors, and layout.\n",
        "3.  Repeat every time the data changes.\n",
        "\n",
        "### The Solution: Code Generation (HTML/CSS)\n",
        "We treat the \"Presentation\" as a \"Software Problem.\" We ask Gemini 3 to act as a **Frontend Developer + UI Designer**.\n",
        "Instead of using a drag-and-drop tool, we instruct the model to **write the code** for a fully interactive, self-contained HTML website that acts as a slide deck.\n",
        "\n",
        "**The Architecture:**\n",
        "1.  **Data Aggregation:** We collect the \"Top Recommendation,\" \"Competitor Stats,\" and \"Market Metrics\" from our previous steps.\n",
        "2.  **Design Prompting:** We give Gemini a \"Design System\" prompt (e.g., \"Use a McKinsey/BCG aesthetic,\" \"Navy Blue color palette,\" \"Card-based layout\").\n",
        "3.  **Autonomous Coding:** Gemini writes the full HTML structure and embedded CSS styles from scratch.\n",
        "\n",
        "**What we will do:**\n",
        "We will execute a single prompt that transforms our raw analysis into a polished, 7-slide executive presentation—instantly."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b8f1c4a2"
      },
      "source": [
        "### Step 1: Format the Context\n",
        "\n",
        "We gather the specific insights generated in Parts 1 through 3—the \"Top Recommendation,\" the \"Viability Score,\" the \"Competitor Counts\"—and bundle them into a clean context object. This ensures the report is populated with our actual findings, not placeholder text.\n",
        "\n",
        "We structure this data into a clear, readable format for the model. Think of this as writing a creative brief for a designer: *\"Here are the facts. Now make them look good.\"*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zErXoZDRHLoY"
      },
      "outputs": [],
      "source": [
        "# @title\n",
        "print(\"=\" * 70)\n",
        "print(\"PART 4: EXECUTIVE REPORT GENERATION\")\n",
        "print(\"=\" * 70)\n",
        "\n",
        "# Create comprehensive structured data for HTML generation\n",
        "print(\"\\n📋 Formatting comprehensive data context for HTML generation...\")\n",
        "\n",
        "# Generate the dynamic parts of the report using list comprehensions, accessing the report object directly.\n",
        "strengths_section = \"\\n\".join(\n",
        "    [\n",
        "        f\"{i}. {s.factor}\\n   Description: {s.description}\\n   Evidence: {s.evidence_from_analysis}\"\n",
        "        for i, s in enumerate(report.top_recommendation.strengths, 1)\n",
        "    ]\n",
        ")\n",
        "\n",
        "concerns_section = \"\\n\".join(\n",
        "    [\n",
        "        f\"{i}. Risk: {c.risk}\\n   Description: {c.description}\\n   Mitigation: {c.mitigation_strategy}\"\n",
        "        for i, c in enumerate(report.top_recommendation.concerns, 1)\n",
        "    ]\n",
        ")\n",
        "\n",
        "alternatives_section = \"\\n\\n\".join(\n",
        "    [\n",
        "        f\"ALTERNATIVE {i}: {alt.location_name}\\nArea: {alt.area}\\nScore: {alt.overall_score}/100\\nOpportunity Type: {alt.opportunity_type}\\nKey Strength: {alt.key_strength}\\nKey Concern: {alt.key_concern}\\nWhy Not Top Choice: {alt.why_not_top}\"\n",
        "        for i, alt in enumerate(report.alternative_locations, 1)\n",
        "    ]\n",
        ")\n",
        "\n",
        "next_steps_section = \"\\n\".join(\n",
        "    [f\"{i}. {step}\" for i, step in enumerate(report.top_recommendation.next_steps, 1)]\n",
        ")\n",
        "\n",
        "key_insights_section = \"\\n\".join(\n",
        "    [f\"{i}. {insight}\" for i, insight in enumerate(report.key_insights, 1)]\n",
        ")\n",
        "\n",
        "# For readability in the f-string, create a few aliases for nested objects\n",
        "top_rec = report.top_recommendation\n",
        "comp = top_rec.competition\n",
        "market = top_rec.market\n",
        "\n",
        "# Build the final data_context string using a single f-string, accessing the report object directly\n",
        "data_context = f\"\"\"\n",
        "LOCATION INTELLIGENCE REPORT - COMPREHENSIVE DATA\n",
        "{\"=\" * 80}\n",
        "\n",
        "ANALYSIS OVERVIEW:\n",
        "- Target Location: {report.target_location}\n",
        "- Business Type: {report.business_type}\n",
        "- Analysis Date: {report.analysis_date}\n",
        "- Market Validation: {report.market_validation}\n",
        "- Total Competitors Found: {report.total_competitors_found}\n",
        "- Zones Analyzed: {report.zones_analyzed}\n",
        "\n",
        "{\"=\" * 80}\n",
        "TOP RECOMMENDATION (PRIMARY - SHOW PROMINENTLY ON SLIDE 1)\n",
        "{\"=\" * 80}\n",
        "\n",
        "Location: {top_rec.location_name}\n",
        "Area: {top_rec.area}\n",
        "Overall Score: {top_rec.overall_score}/100\n",
        "Opportunity Type: {top_rec.opportunity_type}\n",
        "Target Customer Segment: {top_rec.best_customer_segment}\n",
        "Estimated Foot Traffic: {top_rec.estimated_foot_traffic}\n",
        "\n",
        "KEY STRENGTHS:\n",
        "{strengths_section}\n",
        "\n",
        "CONCERNS & MITIGATION:\n",
        "{concerns_section}\n",
        "\n",
        "{\"=\" * 80}\n",
        "COMPETITION ANALYSIS\n",
        "{\"=\" * 80}\n",
        "\n",
        "Total Competitors in Zone: {comp.total_competitors}\n",
        "Competitor Density: {comp.density_per_km2:.2f} competitors/km²\n",
        "Chain Dominance: {comp.chain_dominance_pct:.1f}%\n",
        "Average Competitor Rating: {comp.avg_competitor_rating:.2f} ⭐\n",
        "High-Performing Competitors (4.5+ rating): {comp.high_performers_count}\n",
        "\n",
        "{\"=\" * 80}\n",
        "MARKET CHARACTERISTICS\n",
        "{\"=\" * 80}\n",
        "\n",
        "Population Density: {market.population_density}\n",
        "Income Level: {market.income_level}\n",
        "Infrastructure Access: {market.infrastructure_access}\n",
        "Foot Traffic Pattern: {market.foot_traffic_pattern}\n",
        "Rental Cost Tier: {market.rental_cost_tier}\n",
        "\n",
        "{\"=\" * 80}\n",
        "ALTERNATIVE LOCATIONS\n",
        "{\"=\" * 80}\n",
        "\n",
        "{alternatives_section}\n",
        "\n",
        "{\"=\" * 80}\n",
        "NEXT STEPS (ACTIONABLE)\n",
        "{\"=\" * 80}\n",
        "\n",
        "{next_steps_section}\n",
        "\n",
        "{\"=\" * 80}\n",
        "KEY STRATEGIC INSIGHTS\n",
        "{\"=\" * 80}\n",
        "\n",
        "{key_insights_section}\n",
        "\n",
        "{\"=\" * 80}\n",
        "METHODOLOGY\n",
        "{\"=\" * 80}\n",
        "\n",
        "{report.methodology_summary}\n",
        "\n",
        "{\"=\" * 80}\n",
        "\"\"\"\n",
        "\n",
        "print(\"✅ Comprehensive data context formatted\")\n",
        "print(f\"   • Total context length: {len(data_context):,} characters\")\n",
        "print(\n",
        "    \"   • Includes: Executive summary, top recommendation, competition, market, alternatives, insights, next steps\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3f8a1d5c"
      },
      "source": [
        "### Step 2: The \"Designer\" Prompt\n",
        "Now comes the magic. We prompt Gemini 3 with a dual role:\n",
        "1.  **The Developer:** \"Write valid, bug-free HTML5 and CSS3.\"\n",
        "2.  **The Designer:** \"Use a professional 'Consulting' aesthetic. Use shadows for depth. Use a grid for layout.\"\n",
        "\n",
        "Notice that we don't write a single line of HTML ourselves. The model is responsible for the entire DOM structure and Styling."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7c3e8b9f"
      },
      "outputs": [],
      "source": [
        "# @title\n",
        "# Comprehensive prompt for multi-slide HTML generation\n",
        "html_generation_prompt = f\"\"\"\n",
        "Generate a comprehensive, professional HTML report for a location intelligence analysis.\n",
        "\n",
        "This report should be in the style of McKinsey/BCG consulting presentations:\n",
        "- Multi-slide format using full-screen scrollable sections\n",
        "- Modern, clean, executive-ready design\n",
        "- Data-driven visualizations\n",
        "- Professional color scheme and typography\n",
        "\n",
        "CRITICAL REQUIREMENTS:\n",
        "\n",
        "1. STRUCTURE - Create 7 distinct slides (full-screen sections):\n",
        "\n",
        "   SLIDE 1 - EXECUTIVE SUMMARY & TOP RECOMMENDATION\n",
        "   - Large, prominent display of recommended location and score\n",
        "   - Business type and target location\n",
        "   - High-level market validation\n",
        "   - Eye-catching hero section\n",
        "\n",
        "   SLIDE 2 - TOP RECOMMENDATION DETAILS\n",
        "   - All strengths with evidence (cards/boxes)\n",
        "   - All concerns with mitigation strategies\n",
        "   - Opportunity type and target customer segment\n",
        "\n",
        "   SLIDE 3 - COMPETITION ANALYSIS\n",
        "   - Competition metrics (total competitors, density, chain dominance)\n",
        "   - Visual representation of key numbers (large stat boxes)\n",
        "   - Average ratings, high performers count\n",
        "\n",
        "   SLIDE 4 - MARKET CHARACTERISTICS\n",
        "   - Population density, income level, infrastructure\n",
        "   - Foot traffic patterns, rental costs\n",
        "   - Grid/card layout for each characteristic\n",
        "\n",
        "   SLIDE 5 - ALTERNATIVE LOCATIONS\n",
        "   - Each alternative in a comparison card\n",
        "   - Scores, opportunity types, strengths/concerns\n",
        "   - Why each is not the top choice\n",
        "\n",
        "   SLIDE 6 - KEY INSIGHTS & NEXT STEPS\n",
        "   - Strategic insights (bullet points or cards)\n",
        "   - Actionable next steps (numbered list)\n",
        "\n",
        "   SLIDE 7 - METHODOLOGY\n",
        "   - How the analysis was performed\n",
        "   - Data sources and approach\n",
        "\n",
        "2. DESIGN:\n",
        "   - Use professional consulting color palette:\n",
        "     * Primary: Navy blue (#1e3a8a, #3b82f6) for headers/trust\n",
        "     * Success: Green (#059669, #10b981) for positive metrics\n",
        "     * Warning: Amber (#d97706, #f59e0b) for concerns\n",
        "     * Neutral: Grays (#6b7280, #e5e7eb) for backgrounds\n",
        "   - Modern sans-serif fonts (system: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto)\n",
        "   - Cards with subtle shadows and rounded corners\n",
        "   - Generous white space and padding\n",
        "   - Responsive grid layouts\n",
        "\n",
        "3. TECHNICAL:\n",
        "   - Self-contained: ALL CSS embedded in <style> tag\n",
        "   - No external dependencies (no CDNs, no external images)\n",
        "   - Each slide: min-height: 100vh; page-break-after: always;\n",
        "   - Smooth scroll behavior\n",
        "   - Print-friendly\n",
        "\n",
        "4. DATA TO INCLUDE (use EXACTLY this data, do not invent):\n",
        "\n",
        "{data_context}\n",
        "\n",
        "5. OUTPUT:\n",
        "   - Generate ONLY the complete HTML code\n",
        "   - Start with <!DOCTYPE html>\n",
        "   - End with </html>\n",
        "   - NO explanations before or after the HTML\n",
        "   - NO markdown code fences\n",
        "\n",
        "Make it visually stunning, data-rich, and executive-ready.\n",
        "\n",
        "Current date: {CURRENT_DATE}\n",
        "\"\"\"\n",
        "\n",
        "# Generate the comprehensive HTML report\n",
        "print(\"\\n🎨 Generating comprehensive multi-slide HTML report...\")\n",
        "print(\"   This may take 30-60 seconds due to the complexity...\")\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=html_generation_prompt,\n",
        "    config=types.GenerateContentConfig(temperature=1.0),\n",
        ")\n",
        "\n",
        "# Extract HTML code\n",
        "html_code = response.text.strip(\"```\").strip(\"html\").strip()\n",
        "\n",
        "print(f\"✅ HTML report generated ({len(html_code):,} characters)\")\n",
        "print(\"   Multi-slide consulting-style report with all analysis data\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "a9d2f3e1"
      },
      "source": [
        "### Step 4: The Reveal\n",
        "We render the generated raw HTML directly in the notebook.\n",
        "**Scroll through the output below.** This is not a pre-made template. This entire visual interface—the colors, the typography, the layout of the data cards—was conceived and coded by Gemini 3 in seconds."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "b4c5d6a2"
      },
      "outputs": [],
      "source": [
        "# @title\n",
        "# Display the HTML report in the notebook\n",
        "print(\"\\n📊 Displaying executive report...\\n\")\n",
        "display(HTML(html_code))\n",
        "\n",
        "# Save the HTML to a file\n",
        "report_filename = \"location_intelligence_executive_report.html\"\n",
        "with open(report_filename, \"w\", encoding=\"utf-8\") as f:\n",
        "    f.write(html_code)\n",
        "\n",
        "print(f\"\\n{'=' * 70}\")\n",
        "print(f\"✅ Executive report saved to {report_filename}\")\n",
        "print(\"✅ Open the file in a browser to view the full multi-slide presentation\")\n",
        "print(f\"{'=' * 70}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CIFmIS4luExX"
      },
      "source": [
        "### 🎨 Analysis of the Output\n",
        "\n",
        "**What just happened?**\n",
        "You have just witnessed **End-to-End Autonomous Intelligence**.\n",
        "*   We started with a vague request: *\"I want to open a fitness studio in KR Puram.\"*\n",
        "*   We ended with a fully coded, deployment-ready website presenting a mathematically validated strategy.\n",
        "\n",
        "**Key Capabilities Demonstrated:**\n",
        "1.  **Cross-Domain Competence:** The same model that performed *Geospatial Analysis* (Part 2A) and *Mathematical Gap Analysis* (Part 2B) just demonstrated *UI/UX Design Principles* (Part 4).\n",
        "2.  **Data Fidelity:** Check the analysis on Slide 3 (\"Competition Analysis\"). They match exactly with our Python output from Part 2B. The model successfully maintained data integrity across the entire pipeline.\n",
        "3.  **No-Code Creativity:** You, the user, didn't need to know `<div>` tags or CSS `flexbox`. You simply described the **outcome** you wanted, and the model handled the implementation.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Lrg4m9i8Nr0-"
      },
      "source": [
        "## Bonus 🎉"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6U2_JZxENr0-"
      },
      "source": [
        "Let's generate an infographic with Nano Banana Pro!! 🍌\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "URFACdAgNr0-"
      },
      "source": [
        "This model is a powerful, generalist multimodal model that offers state-of-the-art image generation and conversational image editing capabilities. Nano Banana Pro is also able to show its work, allowing you to see the 'thought process' behind the generated output."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iCdpnxJdOTRn"
      },
      "source": [
        "**NOTE:** Expect higher latency when using this model compared to Gemini 2.5 Flash Image (Nano Banana) as a result of the more advanced capabilities."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZvtE66dkNr0_"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-3-pro-image\"\n",
        "\n",
        "prompt = f\"\"\"\n",
        "Generate an infographic for the following report\n",
        "\n",
        "{data_context}\n",
        "\"\"\"\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=prompt,\n",
        "    config=types.GenerateContentConfig(\n",
        "        response_modalities=[\"IMAGE\", \"TEXT\"],\n",
        "        image_config=types.ImageConfig(\n",
        "            aspect_ratio=\"16:9\",\n",
        "        ),\n",
        "    ),\n",
        ")\n",
        "\n",
        "# Check for errors if an image is not generated\n",
        "if response.candidates[0].finish_reason != types.FinishReason.STOP:\n",
        "    reason = response.candidates[0].finish_reason\n",
        "    raise ValueError(f\"Prompt Content Error: {reason}\")\n",
        "\n",
        "for part in response.candidates[0].content.parts:\n",
        "    if part.thought:\n",
        "        continue  # Skip displaying thoughts\n",
        "    if part.inline_data:\n",
        "        display(Image(data=part.inline_data.data, width=1000))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BK68C-hSNr0_"
      },
      "source": [
        "Exceptional execution by Nano Banana Pro. The leap in quality, high-resolution output, is immediately apparent. This is a powerful tool that sets a new standard for image generation 🚀\n",
        "\n",
        "Check out this [notebook](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/getting-started/intro_gemini_3_image_gen.ipynb) for more Nano Banana Pro!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mDEv4FYuNr0_"
      },
      "source": [
        "## Conclusion: The Future of AI\n",
        "\n",
        "This notebook demonstrated that **Gemini 3 is not just a model; it can act as an orchestrator.**\n",
        "By chaining together distinct cognitive capabilities, we built a sophisticated \"Virtual Employee\" that can:\n",
        "*   👀 **See** the market (Search Grounding)\n",
        "*   🗺️ **Map** the territory (Function Calling)\n",
        "*   🧮 **Calculate** the odds (Code Execution)\n",
        "*   🧠 **Strategize** the move (Extended Reasoning)\n",
        "*   🎨 **Pitch** the result (Code and Image Generation)\n",
        "\n",
        "**Where to go from here?**\n",
        "*   **Scale it:** Wrap this notebook in a `module` to analyze the location in a single go.\n",
        "*   **Deepen it:** Add a \"Rental Price Scraper\" tool to get exact lease costs.\n",
        "*   **Broaden it:** Adapt the prompts to analyze \"Coffee Shops in London\" or \"Warehouses in Texas.\"\n",
        "\n",
        "The architecture remains the same. The world is your dataset."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2fe24a7c"
      },
      "source": [
        "### Try It Yourself!\n",
        "\n",
        "**Experiment with different locations:**\n",
        "```python\n",
        "TARGET_LOCATION = \"Shibuya, Tokyo, Japan\"\n",
        "TARGET_LOCATION = \"Austin, Texas, USA\"\n",
        "TARGET_LOCATION = \"Shoreditch, London, UK\"\n",
        "```\n",
        "\n",
        "**Experiment with different business types:**\n",
        "```python\n",
        "BUSINESS_TYPE = \"fitness studio\"\n",
        "BUSINESS_TYPE = \"fast-casual restaurant\"\n",
        "BUSINESS_TYPE = \"bookstore cafe\"\n",
        "```\n",
        "\n",
        "The notebook adapts to any combination!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dd9289a1"
      },
      "source": [
        "### Additional Resources\n",
        "\n",
        "- [Gemini 3 Documentation](https://ai.google.dev/gemini-api/docs)\n",
        "- [Google Maps Places API](https://developers.google.com/maps/documentation/places/web-service/overview)\n",
        "- [Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing)\n",
        "- [Prompt Engineering Guide](https://ai.google.dev/gemini-api/docs/prompting-intro)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "retail_ai_location_strategy_gemini_3.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
