{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ur8xi4C7S06n"
      },
      "outputs": [],
      "source": [
        "# Copyright 2024 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JAPoU8Sm5E6e"
      },
      "source": [
        "# Creating Marketing Assets using Gemini 2.0\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/marketing/creating_marketing_assets_gemini_2_0.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/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/use-cases/marketing/creating_marketing_assets_gemini_2_0.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/use-cases/marketing/creating_marketing_assets_gemini_2_0.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/use-cases/marketing/creating_marketing_assets_gemini_2_0.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/use-cases/marketing/creating_marketing_assets_gemini_2_0.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/marketing/creating_marketing_assets_gemini_2_0.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/marketing/creating_marketing_assets_gemini_2_0.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/marketing/creating_marketing_assets_gemini_2_0.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/marketing/creating_marketing_assets_gemini_2_0.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": "84f0f73a0f76"
      },
      "source": [
        "| Author |\n",
        "| --- |\n",
        "| [Wan Qi Ang](https://github.com/angwanqi/) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tvgnzT1CKxrO"
      },
      "source": [
        "## Overview\n",
        "\n",
        "The new Google Gen AI SDK provides a unified interface to Gemini 2.0 through both the Gemini Developer API and the Gemini API on Vertex AI. With a few exceptions, code that runs on one platform will run on both. This means that you can prototype an application using the Developer API and then migrate the application to Vertex AI without rewriting your code.\n",
        "\n",
        "In this tutorial, you will learn how to combine the multimodal capabilities of Gemini and Grounding with Google Search to create a marketing campaign brief and marketing assets.\n",
        "\n",
        "You will complete the following tasks:\n",
        "- Get started with the unified Google Gen AI SDK\n",
        "- Create a marketing campaign brief and assets with Gemini, Grounding with Google Search and Controlled Generation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "61RBz8LLbxCR"
      },
      "source": [
        "## Get started"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "No17Cw5hgx12"
      },
      "source": [
        "### Install Google Gen AI SDK\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tFy3H3aPgx12"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet google-genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dmWOrTJ3gx13"
      },
      "source": [
        "### Authenticate your notebook environment (Colab only)\n",
        "\n",
        "If you're running this notebook on Google Colab, run the cell below to authenticate your environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NyKGtVQjgx13"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import auth\n",
        "\n",
        "    auth.authenticate_user()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bFksFuwD9TSg"
      },
      "source": [
        "## Using the Google Gen AI SDK"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IEYbYUbiLiqS"
      },
      "source": [
        "### Import the Google Gen AI SDK and other required libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "j3pDScBD9Wkp"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "import os\n",
        "\n",
        "from IPython.display import Markdown, display\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "from google.genai.types import GenerateContentConfig, GoogleSearch, Tool\n",
        "from pydantic import BaseModel"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uv7-vd3P__AV"
      },
      "source": [
        "### Using Gemini 2.0 Flash with Vertex AI\n",
        "\n",
        "The new Google Gen AI SDK provides a unified interface to Gemini 2.0 Flash through both the Gemini Developer API and the Gemini API in Vertex AI. Gemini 2.0 Flash is also available through Google AI Studio and Vertex AI Studio.\n",
        "\n",
        "- **[Gemini Developer API](https://ai.google.dev/gemini-api/docs)**: Experiment, prototype, and deploy Gen AI projects.\n",
        "- **[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs)**: Build enterprise-ready AI projects on Google Cloud.\n",
        "\n",
        "The Google Gen AI SDK provides a unified interface to these two API services."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mFCKo15iHKdS"
      },
      "source": [
        "#### Vertex AI\n",
        "\n",
        "For those who are looking to build enterprise-ready AI applications in the Cloud you can use [Vertex AI](https://cloud.google.com/vertex-ai?e=48754805&hl=nl). This means that you can prototype an application using the Gemini Developer API and then migrate the application to Vertex AI without rewriting your code. In the following section, we'll take you through steps on how you can switch from Gemini Developer API to Vertex AI.\n",
        "\n",
        "**To get started, you'll need:**\n",
        "1. A Google Cloud Project\n",
        "  - You can choose to [create a new Google Cloud Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) OR\n",
        "  - Reuse an existing project (the same one you used to generate your API key or any other existing projects)\n",
        "2. To enable the [Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)\n",
        "\n",
        "Once your project is all set up, you're ready to switch out your code in the following section!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x7h8QWG4J1Dw"
      },
      "source": [
        "##### **Set Google Cloud project and location information**\n",
        "\n",
        "**Google Cloud Projects**\n",
        "\n",
        "In Google Cloud, projects are the fundamental building blocks for organizing, managing and securing your cloud resources. With projects, you'll be able to easily isolate resources and assign fine-grained permissions to users/service accounts at the project level. This ensures that only authorized individuals can access and manage resources, thereby enhancing security.\n",
        "\n",
        "**Google Cloud Locations**\n",
        "\n",
        "Location is also important as it mainly affects performance and compliance with data regulations:\n",
        "\n",
        "- Performance: Choosing a location closer to your users reduces latency.\n",
        "\n",
        "- Data residency: Your use case, organization or industry might constraint the location of resources.\n",
        "\n",
        "So, selecting the right location for your Google Cloud resources is crucial for optimizing your applications and ensuring you meet your business requirements.\n",
        "\n",
        "**In the next cell, do the following:**\n",
        "- Replace ```PROJECT_ID``` with your Google Cloud project ID"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Nqwi-5ufWp_B"
      },
      "outputs": [],
      "source": [
        "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 = os.environ.get(\"GOOGLE_CLOUD_REGION\", \"us-central1\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9EHmJzed1mA5"
      },
      "outputs": [],
      "source": [
        "# Instantiate client for Vertex AI\n",
        "client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JFX5bZEwMuO0"
      },
      "source": [
        "## Sample Use Case - Creation and Localization of Marketing Assets\n",
        "\n",
        "In this section of the notebook, let's take a look at how we can apply Gemini to a real-world use case.\n",
        "\n",
        "Imagine you're part of a marketing team and you are tasked to create assets for a marketing campaign for the newest phone that your company is launching. As part of this campaign, you'll need to create the following assets:\n",
        "1. Marketing Campaign Brief\n",
        "2. Market Research on the industry\n",
        "2. Social Media Post Ad Copy\n",
        "3. Storyboard for a short-form video\n",
        "\n",
        "Given that your company operates in multiple countries, there is also the added requirement to generate assets in multiple languages such as English, French and Japanese.\n",
        "\n",
        "Let's see how you can use Gemini 2.0 Flash to help you accomplish these tasks!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ij_fQIepC3IY"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.0-flash-001\"  # @param {type: \"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ScGbi2kYPgcd"
      },
      "source": [
        "### Creating a marketing campaign brief using a past campaign as reference"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "91KzAtrscOic"
      },
      "source": [
        "#### Let's have a look at a sample past campaign brief\n",
        "Your team has done a few campaigns for phone launches in the past and documented each campaign's details in the form of a PDF document. These are stored in [Google Cloud Storage (GCS)](https://cloud.google.com/storage?e=48754805&hl=nl), a scalable, secure, and cost-effective object storage solution.\n",
        "\n",
        "Let's have a look at one of the samples."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ejBQqJgKaJSo"
      },
      "outputs": [],
      "source": [
        "# Set the Cloud Storage path\n",
        "marketing_brief_file_path = \"github-repo/generative-ai/gemini2/use-cases/marketing_example/sample_marketing_campaign_brief.pdf\"\n",
        "marketing_brief_file_uri = f\"gs://{marketing_brief_file_path}\"\n",
        "marketing_brief_file_url = f\"https://storage.googleapis.com/{marketing_brief_file_path}\"\n",
        "\n",
        "print(\"Click to view the sample file:\")\n",
        "print(marketing_brief_file_url)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oTvzN1Ika3cD"
      },
      "source": [
        "#### Define response format with Controlled Generation\n",
        "Given the sample marketing campaign brief, we can use Gemini to efficiently extract key details from your past campaign briefs. To take it a step further, we can use [controlled generation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/control-generated-output) which allows you to define a specific schema for the output so that you receive consistently formatted responses. This is particularly useful when you already have an established data schema that you use for other tasks and you'll be able to directly extract data from the model's output without any post-processing.\n",
        "\n",
        "In the next cell, we define the JSON response schema for our marketing campaign brief."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Z10jmIWbdeaK"
      },
      "outputs": [],
      "source": [
        "# JSON response schema for Marketing Campaign Brief\n",
        "\n",
        "\n",
        "class MarketingCampaignBrief(BaseModel):\n",
        "    campaign_name: str\n",
        "    campaign_objectives: list[str]\n",
        "    target_audience: str\n",
        "    media_strategy: list[str]\n",
        "    timeline: str\n",
        "    target_countries: list[str]\n",
        "    performance_metrics: list[str]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KX8sMc3UaOG5"
      },
      "source": [
        "#### Extract details from sample past campaign brief with Gemini 2.0 Flash\n",
        "\n",
        "With our response schema all set, we are ready to send our prompt to Gemini 2.0 Flash! As Gemini 2.0 Flash is multimodal, we'll be able to send the PDF document as part of the input for Gemini to process.\n",
        "\n",
        "When using Vertex AI, you'll be able to pass the file's GCS URL directly to the model instead of having to retrieve and upload it. This makes it convenient for you to build multimodal Gemini-powered apps with seamless integration across Google Cloud. Given Gemini's large context window, GCS provides a scalable and reliable place to store massive datasets, making them readily available for inference.\n",
        "\n",
        "In the next cell, you'll do the following:\n",
        "1. Send the prompt together with the sample past campaign brief PDF to Gemini 2.0 Flash\n",
        "2. Specify that Gemini returns the response in the MarketingCampaignBrief schema you defined previously by including ```response_schema=MarketingCampaignBrief``` in the request"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4jFyKLEeOGrD"
      },
      "outputs": [],
      "source": [
        "prompt = \"\"\"\n",
        "  Extract the details from the sample marketing brief.\n",
        "\"\"\"\n",
        "\n",
        "marketing_brief_file = types.Part.from_uri(\n",
        "    file_uri=marketing_brief_file_url, mime_type=\"application/pdf\"\n",
        ")\n",
        "contents = [marketing_brief_file, prompt]\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=contents,\n",
        "    config=GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=MarketingCampaignBrief,\n",
        "    ),\n",
        ")\n",
        "\n",
        "sample_marketing_brief = response.text\n",
        "sample_marketing_brief_json = json.loads(sample_marketing_brief)\n",
        "print(json.dumps(sample_marketing_brief_json, indent=2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "94xroHNWfXLI"
      },
      "source": [
        "You've successfully extracted the information from the sample past campaign brief PDF document with Gemini 2.0 Flash and Controlled Generation!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dQyEGsAEEnIA"
      },
      "source": [
        "### Conduct market research with Google Search as a tool\n",
        "\n",
        "Next, let's do some market research and find out more about the latest trends in the phone industry so that we can enrich our marketing campaign with the latest information.\n",
        "\n",
        "But how can I do it if LLMs are frozen in time? Here's where Google Search as a tool can be used, to make Gemini more factual and up-to-date by letting you use Gemini with Google Search in real-time to access and incorporate information from the vast expanse of the public web. You should expect reduced hallucinations and increased accuracy.\n",
        "\n",
        "**Here are some incredibly useful applications for grounding:**\n",
        "- Question answering: Get accurate answers to questions that require up-to-date information (e.g., \"What's the latest news on...?\").\n",
        "- Content creation: Generate factual and relevant content on various topics.\n",
        "- Chatbots and conversational AI: Build chatbots that can engage in informed and engaging conversations.\n",
        "\n",
        "In the next cells, let's use Grounding with Google Search to find out more about the latest trends!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VTHhLxgu_FoF"
      },
      "outputs": [],
      "source": [
        "def print_grounding_response(response):\n",
        "    \"\"\"Prints Gemini response with grounding citations.\"\"\"\n",
        "    grounding_metadata = response.candidates[0].grounding_metadata\n",
        "\n",
        "    # Citation indices are in byte units\n",
        "    ENCODING = \"utf-8\"\n",
        "    text_bytes = response.text.encode(ENCODING)\n",
        "\n",
        "    prev_index = 0\n",
        "    markdown_text = \"\"\n",
        "\n",
        "    for grounding_support in grounding_metadata.grounding_supports:\n",
        "        text_segment = text_bytes[\n",
        "            prev_index : grounding_support.segment.end_index\n",
        "        ].decode(ENCODING)\n",
        "\n",
        "        footnotes_text = \"\"\n",
        "        for grounding_chunk_index in grounding_support.grounding_chunk_indices:\n",
        "            footnotes_text += f\"[[{grounding_chunk_index + 1}]]({grounding_metadata.grounding_chunks[grounding_chunk_index].web.uri})\\n\"\n",
        "\n",
        "        markdown_text += f\"{text_segment} {footnotes_text}\\n\"\n",
        "        prev_index = grounding_support.segment.end_index\n",
        "\n",
        "    if prev_index < len(text_bytes):\n",
        "        markdown_text += str(text_bytes[prev_index:], encoding=ENCODING)\n",
        "\n",
        "    markdown_text += \"\\n----\\n## Grounding Sources\\n\"\n",
        "\n",
        "    if grounding_metadata.web_search_queries:\n",
        "        markdown_text += (\n",
        "            f\"\\n**Web Search Queries:** {grounding_metadata.web_search_queries}\\n\"\n",
        "        )\n",
        "        if grounding_metadata.search_entry_point:\n",
        "            markdown_text += f\"\\n**Search Entry Point:**\\n {grounding_metadata.search_entry_point.rendered_content}\\n\"\n",
        "    elif grounding_metadata.retrieval_queries:\n",
        "        markdown_text += (\n",
        "            f\"\\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\\n\"\n",
        "        )\n",
        "\n",
        "    markdown_text += \"### Grounding Chunks\\n\"\n",
        "\n",
        "    for index, grounding_chunk in enumerate(\n",
        "        grounding_metadata.grounding_chunks, start=1\n",
        "    ):\n",
        "        context = grounding_chunk.web or grounding_chunk.retrieved_context\n",
        "        if not context:\n",
        "            print(f\"Skipping Grounding Chunk {grounding_chunk}\")\n",
        "            continue\n",
        "\n",
        "        markdown_text += f\"{index}. [{context.title}]({context.uri})\\n\"\n",
        "\n",
        "    display(Markdown(markdown_text))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-hYkFUxnVsSU"
      },
      "outputs": [],
      "source": [
        "# Use Grounding with Google Search to do market research\n",
        "market_research_prompt = \"\"\"\n",
        "  I am planning to launch a mobile phone campaign and I want to understand the latest trends in the phone industry.\n",
        "  Please answer the following questions:\n",
        "  - What are the latest phone models and their selling point from the top 2 phone makers?\n",
        "  - What is the general public sentiment about mobile phones?\n",
        "\"\"\"\n",
        "\n",
        "contents = [market_research_prompt]\n",
        "\n",
        "google_search_tool = Tool(google_search=GoogleSearch())\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=contents,\n",
        "    config=GenerateContentConfig(tools=[google_search_tool]),\n",
        ")\n",
        "\n",
        "market_research = response.text\n",
        "print_grounding_response(response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7-LBVlhrhj20"
      },
      "source": [
        "Congratulations on using Grounding with Google Search to get the latest information around the phone industry in your market research!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZjMex3LKHMzd"
      },
      "source": [
        "### Putting it together\n",
        "\n",
        "Now that we have a template and some market research done, let's try to create a marketing brief for our new phone launch with Gemini 2.0 Flash!\n",
        "\n",
        "In the next cell, you'll pass the following information to Gemini 2.0 Flash:\n",
        "1. Information about the phone that you're launching\n",
        "2. Prompt to instruct Gemini to create a marketing campaign brief\n",
        "3. Extracted information from the sample past campaign brief\n",
        "4. Market research that was done with Grounding with Google Search\n",
        "5. MarketingCampaignBrief schema that was defined previously\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ksyAm8h0HYpq"
      },
      "outputs": [],
      "source": [
        "new_phone_details = \"\"\"\n",
        "  Phone Name: Pix Phone 10\n",
        "  Short description: Pix Phone 10 is the flagship phone with a focus on AI-powered features and a completely redesigned form factor.\n",
        "  Tech Specs:\n",
        "    - Camera: 50MP main sensor with 48MP ultrawide lens with autofocus for macro shots\n",
        "    - Performance: P5 processor for fast performance and AI capabilities\n",
        "    - Battery: 4700mAh battery for all-day usage\n",
        "  Key Highlights:\n",
        "    - Powerful camera system\n",
        "    - Redesigned software user experience to introduce more fun\n",
        "    - Compact form factor\n",
        "  Launch timeline: Jan 2025\n",
        "  Target countries: US, France and Japan\n",
        "\"\"\"\n",
        "\n",
        "create_brief_prompt = f\"\"\"\n",
        "Given the following details, create a marketing campaign brief for the new phone launch:\n",
        "\n",
        "Sample campaign brief:\n",
        "{sample_marketing_brief}\n",
        "\n",
        "Market research:\n",
        "{market_research}\n",
        "\n",
        "New phone details:\n",
        "{new_phone_details}\n",
        "\"\"\"\n",
        "\n",
        "contents = [create_brief_prompt]\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=contents,\n",
        "    config=GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=MarketingCampaignBrief,\n",
        "    ),\n",
        ")\n",
        "\n",
        "creative_brief = response.text\n",
        "creative_brief_json = json.loads(creative_brief)\n",
        "print(json.dumps(creative_brief_json, indent=2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jjGa1z2rht14"
      },
      "source": [
        "You've successfully created your marketing campaign brief for your upcoming phone launch!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0kUUTkP_KTNl"
      },
      "source": [
        "### Creating Assets for the Marketing Campaign\n",
        "Now that we have our marketing campaign brief for the upcoming phone launch, we can now use it as information and context to generate some marketing assets.\n",
        "\n",
        "Gemini supports a variety of languages ([complete list](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#languages-gemini)) so it is perfect for us as we will need to generate assets in the local language of our target markets: US, France and Japan.\n",
        "\n",
        "In the following sections, we will be looking at creating:\n",
        "- Social Media Ad Copy\n",
        "- Storyboarding for short-form videos"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ME-ot7hmXrB4"
      },
      "source": [
        "#### Creating Social Media Ad Copy\n",
        "Similarly, we will be defining a response schema for ad copy and passing it it to Gemini 2.0 Flash in the request.\n",
        "\n",
        "In the next few cells, we will do the following:\n",
        "1. Define the JSON response schema for our ad copy\n",
        "2. Send the prompt and response schema to Gemini 2.0 Flash"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CBnNzb0DJc92"
      },
      "outputs": [],
      "source": [
        "# JSON response schema for an ad copy\n",
        "\n",
        "\n",
        "class AdCopy(BaseModel):\n",
        "    ad_copy_options: list[str]\n",
        "    localization_notes: list[str]\n",
        "    visual_description: list[str]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "X0PLRHllLttp"
      },
      "outputs": [],
      "source": [
        "ad_copy_prompt = f\"\"\"\n",
        "  Given the marketing campaign brief, create an Instagram ad-copy for each target market: {creative_brief_json[\"target_countries\"]}\n",
        "  Please localize the ad-copy and the visuals to the target markets for better relevancy to the target audience.\n",
        "  Marketing Campaign Brief:\n",
        "  {creative_brief}\n",
        "\"\"\"\n",
        "\n",
        "contents = [ad_copy_prompt]\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=contents,\n",
        "    config=GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=AdCopy,\n",
        "    ),\n",
        ")\n",
        "\n",
        "ad_copy = response.text\n",
        "ad_copy_json = json.loads(ad_copy)\n",
        "print(json.dumps(ad_copy_json, indent=2, ensure_ascii=False))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iF_mmCaUkwgq"
      },
      "source": [
        "You've successfully created localized ad copies for each of the target markets in its respective local language!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1k8qvQ0GXxEz"
      },
      "source": [
        "#### Creating storyboard for short-form videos\n",
        "Lastly, let's get Gemini 2.0 Flash to help us brainstorm a storyboard for a short-form video to accompany the phone launch campaign!\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rDXmBAEDLXkl"
      },
      "outputs": [],
      "source": [
        "short_video_prompt = f\"\"\"\n",
        "  Given the marketing campaign brief, create a storyboard for a YouTube Shorts video for target markets: {creative_brief_json[\"target_countries\"]}.\n",
        "  Please localize the content to the target markets for better relevancy to the target audience.\n",
        "  Marketing Campaign Brief:\n",
        "  {creative_brief}\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "contents = [short_video_prompt]\n",
        "\n",
        "response = client.models.generate_content(model=MODEL_ID, contents=contents)\n",
        "\n",
        "short_video_response = response.text\n",
        "display(Markdown(short_video_response))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_LMu5uAqlS0V"
      },
      "source": [
        "There you go! You've successfully created storyboards for each of the target markets - localized to the local context!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KXnkxZbeM0tY"
      },
      "source": [
        "# Conclusion\n",
        "In this tutorial, you've learned:\n",
        "- How to use the unified Google Gen AI SDK\n",
        "- Extract information from PDF documents\n",
        "- Use Controlled Generation to ensure consistent output in specified schema\n",
        "- Utilize Grounding with Google Search to access latest information\n",
        "- Create a marketing campaign and assets with Gemini"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "dmWOrTJ3gx13"
      ],
      "name": "creating_marketing_assets_gemini_2_0.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
