{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sqi5B7V_Rjim"
      },
      "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": "VyPmicX9RlZX"
      },
      "source": [
        "# Intro to Gemini 2.5 Flash-Lite\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/getting-started/intro_gemini_2_5_flash_lite.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%2Fgemini%2Fgetting-started%2Fintro_gemini_2_5_flash_lite.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/gemini/getting-started/intro_gemini_2_5_flash_lite.ipynb\">\n",
        "      <img src=\"https://www.gstatic.com/images/branding/gcpiconscolors/vertexai/v1/32px.svg\" alt=\"Vertex AI logo\"><br> Open in Vertex AI Workbench\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/getting-started/intro_gemini_2_5_flash_lite.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/gemini/getting-started/intro_gemini_2_5_flash_lite.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/getting-started/intro_gemini_2_5_flash_lite.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/getting-started/intro_gemini_2_5_flash_lite.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/getting-started/intro_gemini_2_5_flash_lite.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/getting-started/intro_gemini_2_5_flash_lite.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": "8MqT58L6Rm_q"
      },
      "source": [
        "| Authors |\n",
        "| --- |\n",
        "| [Eric Dong](https://github.com/gericdong) |\n",
        "| [Holt Skinner](https://github.com/holtskinner) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nVxnv1D5RoZw"
      },
      "source": [
        "## Overview\n",
        "\n",
        "Gemini 2.5 Flash-Lite is Google's most cost-effective Gemini 2.5 model yet, optimized for performance in high-volume workloads. Delivering higher performance than the previous 2.0 Flash and Flash-Lite models and significantly improved latency, it's ideal for tasks like classification, translation, intelligent routing, and other cost-sensitive, high-scale operations.\n",
        "\n",
        "### Objectives\n",
        "\n",
        "In this tutorial, you will learn how to use the Gemini API and the Google Gen AI SDK for Python with the Gemini 2.5 Flash-Lite model.\n",
        "\n",
        "You will complete the following tasks:\n",
        "\n",
        "- Generate text\n",
        "- Control thinking budget\n",
        "- View summarized thoughts\n",
        "- Set model parameters and system instruction\n",
        "- Use safety filters\n",
        "- Use controlled generation\n",
        "- Use search as a tool\n",
        "- Use code execution\n",
        "\n",
        "Gemini 2.5 Flash-Lite also supports other standard Gemini features such as multimodal input, automatic and manual function calling, counting tokens, chat completions. These features are not covered in this tutorial.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gPiTOAHURvTM"
      },
      "source": [
        "## Getting Started"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CHRZUpfWSEpp"
      },
      "source": [
        "### Install the Google Gen AI SDK for Python\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sG3_LKsWSD3A"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet google-genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HlMVjiAWSMNX"
      },
      "source": [
        "### Authenticate your notebook environment\n",
        "\n",
        "If you are running this notebook on Google Colab, run the cell below to authenticate your environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "12fnq4V0SNV3"
      },
      "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": "be18ac9c5ec8"
      },
      "source": [
        "### Authenticate to Vertex AI on Google Cloud\n",
        "\n",
        "You'll need to set up authentication by choosing **one** of the following methods:\n",
        "\n",
        "1.  **Use a Google Cloud Project:** (Recommended for most users)\n",
        "    - See instructions [Set up a project and development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment)\n",
        "2.  **Use a Vertex AI API Key (Express Mode):** For quick experimentation.\n",
        "    - [Get an API Key](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview)\n",
        "    - See tutorial [Getting started with Gemini using Vertex AI in Express Mode](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/getting-started/intro_gemini_express.ipynb).\n",
        "\n",
        "This tutorial uses a Google Cloud Project for authentication."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6wXh1aH7BlPl"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "PROJECT_ID = \"[your-project-id]\"  # @param {type: \"string\", placeholder: \"[your-project-id]\", isTemplate: true}\n",
        "if not PROJECT_ID or PROJECT_ID == \"[your-project-id]\":\n",
        "    PROJECT_ID = str(os.environ.get(\"GOOGLE_CLOUD_PROJECT\"))\n",
        "\n",
        "LOCATION = \"global\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EdvJRUWRNGHE"
      },
      "source": [
        "### Import libraries\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qgdSpVmDbdQ9"
      },
      "outputs": [],
      "source": [
        "from typing import List\n",
        "\n",
        "from IPython.display import HTML, Markdown, display\n",
        "from google import genai\n",
        "from google.genai.types import (\n",
        "    GenerateContentConfig,\n",
        "    GoogleSearch,\n",
        "    HarmBlockThreshold,\n",
        "    HarmCategory,\n",
        "    SafetySetting,\n",
        "    ThinkingConfig,\n",
        "    Tool,\n",
        "    ToolCodeExecution,\n",
        ")\n",
        "from pydantic import BaseModel"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uhAZMeVrCcKS"
      },
      "source": [
        "### Connect to the generative AI service on Vertex AI"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pv_22mKMCjQY"
      },
      "outputs": [],
      "source": [
        "client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "n4yRkFg6BBu4"
      },
      "source": [
        "## Use Gemini 2.5 Flash-Lite\n",
        "\n",
        "Learn more about the [Gemini 2.5 Flash-Lite model](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-flash-lite). The model ID used in this notebook is `gemini-2.5-flash-lite`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-coEslfWPrxo"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash-lite\"  # @param {type: \"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "37CH91ddY9kG"
      },
      "source": [
        "### Send Your First Prompt\n",
        "\n",
        "- Use the `generate_content` method to generate responses to your prompts. You can pass text and other multimodal input to `generate_content`.\n",
        "- Use the `generate_content_stream` method to stream the response as it is being generated, and the model will return chunks of the response as soon as they are generated.\n",
        "- Use the `.text` property to get the text content of the response. By default, Gemini outputs formatted text using [Markdown](https://daringfireball.net/projects/markdown/) syntax."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xRJuHj0KZ8xz"
      },
      "outputs": [],
      "source": [
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"Why is the sky blue?\",\n",
        ")\n",
        "\n",
        "display(Markdown(response.text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hIJVEr0RQY8S"
      },
      "source": [
        "### Set Model Parameters and System Instruction\n",
        "\n",
        "- You can set [Gemini API parameters](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#parameters) in each model request to control how the model generates a response.\n",
        "- A [system instruction](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/system-instruction-introduction) gives the model additional context to understand the task, provide more customized responses, and adhere to guidelines over the user interaction.\n",
        "- You can also configure [safety filters](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-filters) to adjust how the model handles different content categories.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "d9NXP5N2Pmfo"
      },
      "outputs": [],
      "source": [
        "system_instruction = \"\"\"\n",
        "Persona: You are 'The Curator,' a sophisticated AI historian. Your tone is eloquent and engaging.\n",
        "Task: Create a thematic travel itinerary that creatively combines the user's interests.\n",
        "Rules:\n",
        "- Use Markdown for all formatting.\n",
        "- Each day must have a ### Theme:.\n",
        "- Every day must include these exact bolded sections: Morning:, Afternoon:, Evening:, The Curator's Note:, and Required Attire:.\n",
        "- Directly connect the itinerary to all of the user's stated interests.\n",
        "\"\"\"\n",
        "\n",
        "prompt = \"\"\"\n",
        "Destination: Florence, Italy\n",
        "Duration: 2 Days\n",
        "Interests: Medici family banking and the use of light/optics in Renaissance art.\n",
        "Goal: Create an itinerary showing how money and light converged to create Florentine masterpieces.\n",
        "\"\"\"\n",
        "\n",
        "safety_settings = [\n",
        "    SafetySetting(\n",
        "        category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,\n",
        "        threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,\n",
        "    ),\n",
        "]\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=prompt,\n",
        "    config=GenerateContentConfig(\n",
        "        system_instruction=system_instruction,\n",
        "        temperature=0.7,\n",
        "        top_p=0.95,\n",
        "        candidate_count=1,\n",
        "        max_output_tokens=2048,\n",
        "        safety_settings=safety_settings,\n",
        "    ),\n",
        ")\n",
        "\n",
        "display(Markdown(response.text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EBtGmbvaD9Mk"
      },
      "source": [
        "### Control Thinking Budget\n",
        "\n",
        "Gemini 2.5 Flash-Lite is a hybrid reasoning model that can apply an extended amount of thinking to tasks and use tools to maximize response accuracy.  Unlike Gemini 2.5 Flash, the thinking mode is OFF by default in Gemini 2.5 Flash-Lite. You can set the optional `thinking_budget` parameter to control how much the model thinks for a given prompt.\n",
        "\n",
        "\n",
        "- `thinking_budget=0` : Thinking OFF (default)\n",
        "- `thinking_budget=-1`: Dynamic thinking\n",
        "- `thinking_budget=[512-24576]`: Allocate thinking budget\n",
        "\n",
        "Then use the `generate_content` or `generate_content_stream` method to send a request to generate content with the `ThinkingConfig`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6LT7dm2FDTo3"
      },
      "outputs": [],
      "source": [
        "THINKING_BUDGET = 1024  # @param {type: \"integer\"}\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"How many R's are in the word strawberry?\",\n",
        "    config=GenerateContentConfig(\n",
        "        thinking_config=ThinkingConfig(\n",
        "            include_thoughts=True,\n",
        "            thinking_budget=THINKING_BUDGET,\n",
        "        )\n",
        "    ),\n",
        ")\n",
        "\n",
        "display(Markdown(response.text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BzXrgiUTzsPw"
      },
      "source": [
        "Optionally, you can print the `usage_metadata` and token counts from the model response."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xOiHH_vCymZ_"
      },
      "outputs": [],
      "source": [
        "print(f\"prompt_token_count: {response.usage_metadata.prompt_token_count}\")\n",
        "print(f\"candidates_token_count: {response.usage_metadata.candidates_token_count}\")\n",
        "print(f\"thoughts_token_count: {response.usage_metadata.thoughts_token_count}\")\n",
        "print(f\"total_token_count: {response.usage_metadata.total_token_count}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e59e82a73a3e"
      },
      "source": [
        "### View Summarized Thoughts\n",
        "\n",
        "You can set the `include_thoughts` flag to `True` to have the model return a summary of its \"thoughts\" in addition to the final answer.  When you make a request with this setting, the response will contain multiple parts.  You can check the `part.thought` field to identify which part contains the model's thoughts."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2cd0767506a6"
      },
      "outputs": [],
      "source": [
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"How many R's are in the word strawberry?\",\n",
        "    config=GenerateContentConfig(\n",
        "        thinking_config=ThinkingConfig(include_thoughts=True, thinking_budget=-1)\n",
        "    ),\n",
        ")\n",
        "\n",
        "for part in response.candidates[0].content.parts:\n",
        "    if part.thought:\n",
        "        display(Markdown(f\"**Thoughts**: {part.text}\"))\n",
        "    else:\n",
        "        display(Markdown(f\"**Answer**: {part.text}\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y0GaUgecqXLy"
      },
      "source": [
        "## Use Controlled Generation\n",
        "\n",
        "Controlled generation allows you to define a response schema to specify the structure of the model's output, including field names and expected data types.  The model's output will strictly follow the provided schema."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eqHIrPOPpflz"
      },
      "outputs": [],
      "source": [
        "class Recipe(BaseModel):\n",
        "    name: str\n",
        "    description: str\n",
        "    ingredients: list[str]\n",
        "\n",
        "\n",
        "class RecipeList(BaseModel):\n",
        "    recipes: List[Recipe]\n",
        "\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"List a few popular cookie recipes and their ingredients.\",\n",
        "    config=GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=RecipeList,\n",
        "    ),\n",
        ")\n",
        "\n",
        "recipes: List[Recipe] = response.parsed\n",
        "for recipe in recipes.recipes:\n",
        "    print(f\"Recipe: {recipe.name}\")\n",
        "    print(f\"Ingredients: {recipe.ingredients}\")\n",
        "    print(\"\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_BsP0vXOY7hg"
      },
      "source": [
        "## Grounding with Google Search (Search as a Tool)\n",
        "\n",
        "Google Search is available as a built-in tool in Gemini 2.5 Flash-Lite, which is not a feature of the 2.0 Flash-Lite model.  This allows the model to decide when to use Google Search to improve the accuracy and recency of its responses."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yeR09J3AZT4U"
      },
      "outputs": [],
      "source": [
        "google_search_tool = Tool(google_search=GoogleSearch())\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"What is the current temperature in Austin, TX?\",\n",
        "    config=GenerateContentConfig(\n",
        "        tools=[google_search_tool],\n",
        "    ),\n",
        ")\n",
        "\n",
        "display(Markdown(response.text))\n",
        "\n",
        "HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MhDs2X3o0neK"
      },
      "source": [
        "## Code Execution\n",
        "\n",
        "The Gemini API's code execution feature enables the model to generate and run Python code.  The model can learn iteratively from the code's results to arrive at a final output."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1W-3c7sy0nyz"
      },
      "outputs": [],
      "source": [
        "code_execution_tool = Tool(code_execution=ToolCodeExecution())\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=\"Calculate 20th fibonacci number. Then find the nearest palindrome to it.\",\n",
        "    config=GenerateContentConfig(\n",
        "        tools=[code_execution_tool],\n",
        "        temperature=0,\n",
        "    ),\n",
        ")\n",
        "\n",
        "display(\n",
        "    Markdown(\n",
        "        f\"\"\"\n",
        "## Code\n",
        "```py\n",
        "{response.executable_code}\n",
        "```\n",
        "### Output\n",
        "```\n",
        "{response.code_execution_result}\n",
        "```\n",
        "\"\"\"\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eQwiONFdVHw5"
      },
      "source": [
        "## What's next\n",
        "\n",
        "- Explore other notebooks in the [Google Cloud Generative AI GitHub repository](https://github.com/GoogleCloudPlatform/generative-ai).\n",
        "- Explore AI models in [Model Garden](https://cloud.google.com/vertex-ai/generative-ai/docs/model-garden/explore-models)."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "intro_gemini_2_5_flash_lite.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
