{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ur8xi4C7S06n"
      },
      "outputs": [],
      "source": [
        "# Copyright 2025 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "84f0f73a0f76"
      },
      "source": [
        "| | |\n",
        "|-|-|\n",
        "| Author(s) |  [Mohammad Al-Ansari](https://github.com/mansari/) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JAPoU8Sm5E6e"
      },
      "source": [
        "# Productivity Coaching with Gemini and Google Calendar\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/productivity/productivity_coaching_with_google_calendar.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%2Fuse-cases%2Fproductivity%2Fproductivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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/productivity/productivity_coaching_with_google_calendar.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": "mzi17id6IXv-"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This notebook demonstrates how to use Gemini as a personal productivity coach by leveraging external APIs, specifically the Google Calendar API.\n",
        "\n",
        "Gemini is a family of generative AI models developed by [Google DeepMind](https://deepmind.google/) designed for multimodal use cases. [Gemini 2.0](https://cloud.google.com/vertex-ai/generative-ai/docs/gemini-v2) is the latest model version.\n",
        "\n",
        "## Objectives\n",
        "\n",
        "In this notebook, you will learn how to use Gemini's tools feature, along with the Gen AI SDK and Google API SDK for Python, to:\n",
        "\n",
        "* Analyze a screenshot of a calendar for productivity gains\n",
        "* Add Google Calendar API as a tool that Gemini can use\n",
        "* Analyze your own calendar to identify productivity gains\n",
        "* Learn more about your productivity style and get coaching tips"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dSxKV-CIH9oa"
      },
      "source": [
        "### Costs\n",
        "\n",
        "This tutorial uses billable components of Google Cloud:\n",
        "\n",
        "- Vertex AI\n",
        "\n",
        "Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "61RBz8LLbxCR"
      },
      "source": [
        "## Getting Started"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "No17Cw5hgx12"
      },
      "source": [
        "### Install Google Gen AI SDK and Google API SDK for Python"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tFy3H3aPgx12"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet google-genai google-api-python-client"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5303c05f7aa6"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6fc324893334"
      },
      "outputs": [],
      "source": [
        "from IPython.display import Markdown, display\n",
        "from google import genai\n",
        "from google.genai.types import GenerateContentConfig, Part"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dmWOrTJ3gx13"
      },
      "source": [
        "### Authenticate your notebook environment (Colab only)\n",
        "\n",
        "If you are running this notebook on Google Colab, run the following cell to authenticate your environment. This step is not required if you are using [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NyKGtVQjgx13"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "# Additional authentication is required for Google Colab\n",
        "if \"google.colab\" in sys.modules:\n",
        "    # Authenticate user to Google Cloud\n",
        "    from google.colab import auth\n",
        "\n",
        "    auth.authenticate_user()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v8YW7MCx_O6G"
      },
      "source": [
        "### Set Google Cloud project information and create client\n",
        "\n",
        "To get started using Vertex AI, you must have an existing Google Cloud project and [enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
        "\n",
        "Learn more about [setting up a project and a development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YwFoe0T9_Ek0"
      },
      "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 = os.environ.get(\"GOOGLE_CLOUD_REGION\", \"us-central1\")\n",
        "\n",
        "client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "X_cgnwxgOHGY"
      },
      "source": [
        "### Configure Google Calendar API access"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oL6KigDV6NSG"
      },
      "source": [
        "#### Enable Google Calendar API\n",
        "\n",
        "To start using the Google Calendar API, you must first [enable it](https://console.cloud.google.com/flows/enableapi?apiid=calendar-json.googleapis.com)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Lngat8co4a34"
      },
      "source": [
        "#### Connect your Google Workspace account\n",
        "\n",
        "To access your calendar data, you will need to provide credential details. You will use [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authorize access to your Google Calendar.\n",
        "\n",
        "Google Workspace APIs, including Calendar API, have usage limits known as [quotas](https://cloud.google.com/docs/quotas/overview). Specifying your project ensures that the correct quotas are applied when accessing your data.\n",
        "\n",
        "**Steps to Connect:**\n",
        "\n",
        "1.  **Execute the code below.** This initiates the authentication process.\n",
        "2.  **Confirm if prompted:** Click on the blinking cursor on the output window, type `Y` and press Enter to proceed.\n",
        "3.  **Grant Permissions in your browser:** A link to a Google authorization page will be displayed. Click the link and follow the prompts to grant the required access to your calendar data.\n",
        "4.  **Copy the Authorization Code:** After granting permission, you will receive a code on the screen. Copy the provided code.\n",
        "5.  **Paste and Enter:** Click on the blinking cursor, paste the copied code into the notebook's output and press Enter to complete the authentication."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SKenTDdj5NUu"
      },
      "outputs": [],
      "source": [
        "!gcloud auth application-default login --project \"$PROJECT_ID\" \\\n",
        "  --scopes https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/calendar.events.readonly"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d5zLisT-ostz"
      },
      "source": [
        "<div class=\"alert alert-block alert-warning\">\n",
        "<b>⚠️ Important:</b> The credentials obtained during this process are stored in memory and are valid only for the current session. If the runtime is terminated, you will need to re-authorize. ⚠️\n",
        "</div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e43229f3ad4f"
      },
      "source": [
        "### Load Gemini 2.0 Flash model\n",
        "\n",
        "Learn more about all [Gemini models on Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-models)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cf93d5f0ce00"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.0-flash-001\"  # @param {type: \"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LVEy_dM5FEgR"
      },
      "source": [
        "## Set up system instructions\n",
        "\n",
        "Before you dive into analyzing your data, let's configure Gemini with clear instructions. These [system instructions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/system-instruction-introduction) tell Gemini it's your productivity coach, allowing it to provide tailored analysis."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0paF3u5uFEET"
      },
      "outputs": [],
      "source": [
        "system_instruction = \"\"\"\n",
        "You are a productivity coach. Your role is to analyze a user's calendar events\n",
        "to offer actionable recommendations for improvement and determine their\n",
        "productivity style.\n",
        "\n",
        "In your analysis, consider:\n",
        "\n",
        "* **Time management:** Efficiency of time allocation and scheduling patterns.\n",
        "* **Collaboration:** Patterns of meetings and collaborative work.\n",
        "* **Task prioritization:** Methods of prioritizing tasks and potential\n",
        "procrastination.\n",
        "* **Work-life balance:** Indicators of healthy work-life integration.\n",
        "\n",
        "Provide specific, actionable recommendations to improve the user's productivity,\n",
        " time management, communication, and overall well-being.\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pyrOSJi2WPKp"
      },
      "source": [
        "## Analyze sample calendar images\n",
        "\n",
        "Before you connect to live data, let's test Gemini's ability to analyze calendar images.\n",
        "\n",
        "You have two sample calendars available: one for a _Developer Advocate_ and another for a _Machine Learning Team Lead_.  Both are accessible from a Google Cloud Storage bucket and can be loaded using `Part.from_uri`.\n",
        "\n",
        "Take a look at the sample calendars:\n",
        "\n",
        "* [Developer Advocate Calendar](https://storage.googleapis.com/github-repo/generative-ai/gemini/use-cases/productivity/productivity_coaching_with_google_calendar_and_gmail/DevRel_Schedule.png)\n",
        "* [Machine Learning Team Lead Calendar](https://storage.googleapis.com/github-repo/generative-ai/gemini/use-cases/productivity/productivity_coaching_with_google_calendar_and_gmail/ML_Lead_Schedule.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0t3avJIcEEpi"
      },
      "outputs": [],
      "source": [
        "image_filename = \"DevRel_Schedule.png\"  # or \"ML_Lead_Schedule.png\"\n",
        "\n",
        "base_path = \"gs://github-repo/generative-ai/gemini/use-cases/productivity/productivity_coaching_with_google_calendar_and_gmail/\"\n",
        "image_file_uri = f\"{base_path}{image_filename}\"\n",
        "\n",
        "calendar_image_part = Part.from_uri(\n",
        "    file_uri=image_file_uri,\n",
        "    mime_type=\"image/png\",\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FyJoPvWlWWPI"
      },
      "outputs": [],
      "source": [
        "prompt = \"\"\"\n",
        "Analyze this screenshot of my weekly schedule and identify ways to improve\n",
        "my productivity and work-life balance.\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=[\n",
        "        calendar_image_part,\n",
        "        prompt,\n",
        "    ],\n",
        "    config=GenerateContentConfig(\n",
        "        system_instruction=system_instruction,\n",
        "    ),\n",
        ")\n",
        "calendar_analysis = response.text\n",
        "display(Markdown(calendar_analysis))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AWy4-5ZYXsM0"
      },
      "source": [
        "## Connect Google Calendar API\n",
        "\n",
        "You will now integrate Gemini with the Google Calendar API using [function calling](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling). This allows Gemini to dynamically access your current calendar ensuring its responses are based on live data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "grpNHeG8lfJ9"
      },
      "outputs": [],
      "source": [
        "import datetime\n",
        "from typing import Any\n",
        "\n",
        "from googleapiclient.discovery import build\n",
        "from googleapiclient.errors import HttpError\n",
        "\n",
        "\n",
        "def get_next_n_calendar_events(num_of_events: int = 10) -> list[dict[str, Any]]:\n",
        "    \"\"\"\n",
        "    Retrieves upcoming events from a Google Calendar primary calendar.\n",
        "\n",
        "    Requires valid Google Cloud credentials with Calendar API access.\n",
        "\n",
        "    Args:\n",
        "        num_of_events: The maximum number of events to retrieve (defaults to 10, max 250).\n",
        "\n",
        "    Returns:\n",
        "        A list of dictionaries, each representing an event with 'summary', 'start', 'end', and 'status'.\n",
        "        Date/time values are strings in RFC3339 format (e.g., '2024-07-19T10:00:00-04:00').\n",
        "        Returns an empty list if no events are found or if an error occurs.  Errors are logged.\n",
        "\n",
        "    Raises:\n",
        "        ValueError: If num_of_events is invalid.\n",
        "    \"\"\"\n",
        "    if not 1 <= num_of_events <= 250:\n",
        "        raise ValueError(\"num_of_events must be between 1 and 250.\")\n",
        "\n",
        "    try:\n",
        "        service = build(\"calendar\", \"v3\")\n",
        "        now = datetime.datetime.utcnow().isoformat() + \"Z\"\n",
        "        events_result = (\n",
        "            service.events()\n",
        "            .list(\n",
        "                calendarId=\"primary\",\n",
        "                timeMin=now,\n",
        "                maxResults=num_of_events,\n",
        "                singleEvents=True,\n",
        "                orderBy=\"startTime\",\n",
        "            )\n",
        "            .execute()\n",
        "        )\n",
        "        events = events_result.get(\"items\", [])\n",
        "\n",
        "        # Concise list comprehension for extracting event data\n",
        "        essential_events = [\n",
        "            {\n",
        "                \"summary\": event.get(\"summary\"),\n",
        "                \"start\": event.get(\"start\", {}).get(\"dateTime\"),\n",
        "                \"end\": event.get(\"end\", {}).get(\"dateTime\"),\n",
        "                \"status\": event.get(\"status\"),\n",
        "            }\n",
        "            for event in events\n",
        "        ]\n",
        "        return essential_events\n",
        "\n",
        "    except HttpError as error:\n",
        "        print(f\"An error occurred: {error}\")\n",
        "        return []"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9VKQhu-vJ34S"
      },
      "source": [
        "## Get productivity insights based on your Google Calendar events\n",
        "\n",
        "You will now use the Google Calendar API tool to prompt Gemini to analyze your calendar events. This analysis can reveal insights into various aspects of your work style, including meeting habits and collaboration patterns.\n",
        "\n",
        "You will also ask Gemini to identify your unique productivity archetype and style, offering deeper insights into your individual work habits and communication patterns."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "o3rDNCuV8KQ1"
      },
      "outputs": [],
      "source": [
        "prompt = \"\"\"\n",
        "Analyze my upcoming 25 calendar events to provide practical suggestions for\n",
        "optimizing my schedule and increasing productivity.\n",
        "\n",
        "Additionally, identify and explain my productivity archetype and style,\n",
        "including its key characteristics, strengths, and weaknesses. Based on this\n",
        "analysis, offer actionable recommendations to improve my workflow, time\n",
        "management, and communication.\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.9,\n",
        "        tools=[get_next_n_calendar_events],\n",
        "    ),\n",
        ")\n",
        "calendar_analysis = response.text\n",
        "display(Markdown(calendar_analysis))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vZ6BAQHVNU9A"
      },
      "source": [
        "## Conclusion\n",
        "\n",
        "You've successfully extended Gemini to analyze your personal schedule and communication styles and gain valuable insights into your productivity. By integrating with Google Calendar you've enabled personalized recommendations based on your real-time data.\n",
        "\n",
        "This is just the beginning! Explore extending this analysis to other Google Workspace data, like Google Docs or Drive. With Gemini as your AI productivity coach, optimize your workflow, enhance communication, and achieve a better work-life balance.\n",
        "\n",
        "Ready to take it further? Expand this use case by building a [Google Workspace Add-on](https://developers.google.com/workspace/add-ons) or a [Google Chat app](https://developers.google.com/workspace/chat). Check out the [Google Workspace Developer documentation](https://developers.google.com/workspace) for more information."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "productivity_coaching_with_google_calendar.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
