{
  "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": [
        "# AI Agents for Engineers (Evolution of AI Agents)\n",
        "\n",
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/workshops/ai-agents/ai_agents_for_engineers.ipynb\">\n",
        "  <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
        "</a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "84f0f73a0f76"
      },
      "source": [
        "| | |\n",
        "|-|-|\n",
        "| Author(s) | [Kristopher Overholt](https://github.com/koverholt) [Holt Skinner](https://github.com/holtskinner)|"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tvgnzT1CKxrO"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This notebook demonstrates 3 different approaches to generating essays using the [Gemini Developer API](https://ai.google.dev/gemini-api/docs) or [Gemini API in Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs). Each method illustrates a distinct paradigm for running AI Agents in differing levels of complexity.\n",
        "\n",
        "1. Zero-Shot Approach with the Gemini API\n",
        "2. Step-by-Step Approach With LangChain\n",
        "3. Iterative, AI-Agent Approach with LangGraph"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "61RBz8LLbxCR"
      },
      "source": [
        "## Get started"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "No17Cw5hgx12"
      },
      "source": [
        "### Install Gemini SDK and other required packages\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tFy3H3aPgx12"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --quiet \\\n",
        "    google-genai \\\n",
        "    langgraph \\\n",
        "    langchain \\\n",
        "    langchain-google-genai \\\n",
        "    langchain-google-vertexai \\\n",
        "    langchain-community \\\n",
        "    tavily-python \\\n",
        "    pydantic"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R5Xep4W9lq-Z"
      },
      "source": [
        "### Restart runtime\n",
        "\n",
        "To use the newly installed packages in this Jupyter runtime, you must restart the runtime. You can do this by running the cell below, which restarts the current kernel.\n",
        "\n",
        "The restart might take a minute or longer. After it's restarted, continue to the next step."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XRvKdaPDTznN"
      },
      "outputs": [],
      "source": [
        "import IPython\n",
        "\n",
        "app = IPython.Application.instance()\n",
        "app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SbmM4z7FOBpM"
      },
      "source": [
        "<div class=\"alert alert-block alert-warning\">\n",
        "<b>⚠️ The kernel is going to restart. Wait until it's finished before continuing to the next step. ⚠️</b>\n",
        "</div>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b1824bd79df4"
      },
      "source": [
        "### Configure Tavily\n",
        "\n",
        "Get an API key for [Tavily](https://tavily.com/), a web search API for Generative AI models."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "5df2f86c691f"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "os.environ[\"TAVILY_API_KEY\"] = \"YOUR_API_KEY_HERE\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "e00844b64cf7"
      },
      "outputs": [],
      "source": [
        "# If your API Keys are in Colab Secrets\n",
        "import sys\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import userdata\n",
        "\n",
        "    os.environ[\"TAVILY_API_KEY\"] = userdata.get(\"TAVILY_API_KEY\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0781fd4c9001"
      },
      "source": [
        "### Configure Gemini Developer API\n",
        "\n",
        "Get API keys from [Google AI Studio](https://ai.google.dev/gemini-api/docs/api-key) and [Tavily](https://tavily.com/)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f2d2ecd0e96d"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "os.environ[\"GOOGLE_API_KEY\"] = \"YOUR_API_KEY_HERE\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nvuDx1V6buOQ"
      },
      "outputs": [],
      "source": [
        "# If your API Keys are in Colab Secrets\n",
        "import sys\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import userdata\n",
        "\n",
        "    os.environ[\"GOOGLE_API_KEY\"] = userdata.get(\"GOOGLE_API_KEY\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5ffb0f859dde"
      },
      "source": [
        "### Configure Vertex AI\n",
        "\n",
        "**Use a Google Cloud Project:** This requires enabling the Vertex AI API in your Google Cloud project.\n",
        "\n",
        "[Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "885a3c84ddac"
      },
      "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": "code",
      "execution_count": 4,
      "metadata": {
        "id": "c80118166880"
      },
      "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\")\n",
        "\n",
        "os.environ[\"GOOGLE_GENAI_USE_VERTEXAI\"] = \"true\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EdvJRUWRNGHE"
      },
      "source": [
        "## Generating Essays Using a Zero-Shot Approach with the Gemini API\n",
        "\n",
        "With just a single call to the `generate_content` method, users can create detailed, structured essays on any topic by leveraging state-of-the-art language models such as Gemini 2.0 or Gemini 2.0.\n",
        "\n",
        "<img src=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/workshops/ai-agents/1-prompt-essay.png?raw=1\" width=\"350px\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5303c05f7aa6"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "6fc324893334"
      },
      "outputs": [],
      "source": [
        "from IPython.display import Markdown, display"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4631829d00c8"
      },
      "source": [
        "### Create Client"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "898c62c59d40"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "\n",
        "client = genai.Client()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4b87f1f593d5"
      },
      "source": [
        "Verify which API you are using."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "84c16a5f3f33"
      },
      "outputs": [],
      "source": [
        "if not client.vertexai:\n",
        "    print(f\"Using Gemini Developer API.\")\n",
        "elif client._api_client.project:\n",
        "    print(\n",
        "        f\"Using Vertex AI with project: {client._api_client.project} in location: {client._api_client.location}\"\n",
        "    )\n",
        "elif client._api_client.api_key:\n",
        "    print(\n",
        "        f\"Using Vertex AI in express mode with API key: {client._api_client.api_key[:5]}...{client._api_client.api_key[-5:]}\"\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e43229f3ad4f"
      },
      "source": [
        "### Load model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "cf93d5f0ce00"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.0-flash-001\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbcd4f57190f"
      },
      "source": [
        "### Make an API call to generate the essay"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "3734f520c1b3"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Heat transfer is a critical consideration in the design and operation of modern data centers, as the concentration of high-powered computing equipment generates tremendous amounts of heat. Effective heat management is essential for maintaining optimal performance, preventing equipment failure, and ensuring energy efficiency. Various heat transfer mechanisms, including conduction, convection, and radiation, are leveraged in innovative cooling solutions. For instance, cold plates directly attached to CPUs and GPUs conduct heat away, while air and liquid cooling systems rely on convection to dissipate heat from the components to the surrounding environment. The use of phase-change materials and heat pipes further enhances heat transfer efficiency, enabling higher densities and improved reliability in data center operations.\n",
              "\n",
              "Modern data centers employ a range of sophisticated cooling technologies to manage the generated heat effectively. Air cooling, once the dominant method, is now often augmented with liquid cooling solutions, particularly for high-density deployments. Direct-to-chip liquid cooling offers superior thermal performance compared to air cooling, allowing for higher clock speeds and reduced fan noise. Rear door heat exchangers and immersion cooling systems further enhance heat dissipation by capturing heat directly from the exhaust air or submerging the equipment in a dielectric fluid. Computational fluid dynamics (CFD) simulations are used to model airflow and temperature distribution within the data center, enabling optimized placement of cooling units and servers for efficient heat removal.\n",
              "\n",
              "The implementation of advanced heat transfer technologies in data centers not only improves equipment reliability and performance but also contributes to significant energy savings and reduced environmental impact. By optimizing cooling systems, data centers can minimize their power consumption, lowering operating costs and decreasing their carbon footprint. Furthermore, waste heat recovery systems can capture and repurpose the excess heat generated by the servers, utilizing it for building heating or other applications, further improving energy efficiency and sustainability. As data centers continue to evolve and house increasingly powerful computing hardware, the effective management of heat transfer will remain a crucial challenge and a key enabler of their continued growth and success.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "prompt = \"Write a 3-paragraph essay about the application of heat transfer in modern data centers\"\n",
        "\n",
        "response = client.models.generate_content(model=MODEL_ID, contents=prompt)\n",
        "display(Markdown(response.text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "520e23ea4332"
      },
      "source": [
        "---\n",
        "\n",
        "However, what if we ask the model to write an essay about an event that happened more recently and the LLM doesn't inherently know about that event?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "dcb775b83997"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "While specific details regarding the impact of hypothetical 2024 hurricanes Helene and Milton are impossible to predict without them actually occurring, we can discuss the *potential* ramifications based on hurricane characteristics and historical precedent. A major impact would undoubtedly be widespread damage to infrastructure, particularly in coastal communities. Strong winds could topple power lines, leaving residents without electricity for extended periods, while torrential rainfall could lead to catastrophic flooding, damaging homes, businesses, and critical transportation networks. Depending on the intensity and track, these storms could trigger evacuations, straining local resources and potentially causing displacement of entire populations. Moreover, the economic repercussions would be significant, affecting tourism, agriculture, and the fishing industry.\n",
              "\n",
              "Beyond the immediate physical damage, both hurricanes could have devastating effects on human lives and well-being. Injuries and fatalities are always a concern, particularly amongst vulnerable populations with limited access to resources or residing in flood-prone areas. The stress and trauma associated with experiencing a natural disaster can lead to long-term mental health issues, requiring extensive support services. Disruption to healthcare facilities and emergency services could further exacerbate the crisis, hindering rescue and recovery efforts. In the aftermath, access to clean water, food, and shelter would become paramount concerns, demanding a coordinated response from governmental and non-governmental organizations.\n",
              "\n",
              "Looking at the broader picture, Hurricanes Helene and Milton, even if categorized as less intense storms, could significantly impact the environment. Coastal erosion and beach degradation would be likely, altering shorelines and potentially endangering fragile ecosystems. Runoff from floodwaters could contaminate water supplies and spread pollutants, impacting both human and marine life. The destruction of habitats could lead to displacement of wildlife and disruption of ecological balance. Ultimately, the scale of the impact would depend on a confluence of factors, including the storms' intensity, track, and the preparedness levels of affected communities, highlighting the crucial need for robust disaster preparedness and mitigation strategies.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "prompt = \"Write a 3-paragraph essay about the impacts of Hurricane Helene and Hurricane Milton in 2024.\"\n",
        "response = client.models.generate_content(model=MODEL_ID, contents=prompt)\n",
        "display(Markdown(response.text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "764ce71aecd5"
      },
      "source": [
        "In this case, the model had no information about these recent events and was unable to write an effective essay."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "16aafc60d80b"
      },
      "source": [
        "## Generating Essays Using a Step-by-Step Approach With LangChain\n",
        "\n",
        "This step demonstrates how to build an essay-writing pipeline using [LangChain](https://www.langchain.com/), the [Gemini API in Google AI Studio](https://ai.google.dev/gemini-api/docs), and [Tavily](https://tavily.com/) for search.\n",
        "\n",
        "By combining these tools, we create a seamless workflow that plans an essay outline, performs web searches for relevant information, and generates a complete essay draft based on the collected data.\n",
        "\n",
        "This solution showcases the power of chaining LLM models and external tools to tackle complex tasks with minimal human intervention, providing a robust approach to automated content generation.\n",
        "\n",
        "<img src=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/workshops/ai-agents/2-langchain-essay.png?raw=1\" width=\"550px\">\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "85666976a359"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "29d6e42d27ae"
      },
      "outputs": [],
      "source": [
        "from IPython.display import Markdown, display\n",
        "from langchain import LLMChain\n",
        "from langchain.prompts import ChatPromptTemplate\n",
        "from langchain_community.tools import TavilySearchResults\n",
        "from langchain_core.output_parsers import StrOutputParser\n",
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "from langchain_google_vertexai import ChatVertexAI"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "43392590b1d8"
      },
      "source": [
        "### Initialize Gemini model & search tool"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "6f8b0c205551"
      },
      "outputs": [],
      "source": [
        "if client.vertexai:\n",
        "    model = ChatVertexAI(project=PROJECT_ID, model=MODEL_ID, temperature=0)\n",
        "else:\n",
        "    model = ChatGoogleGenerativeAI(model=MODEL_ID, temperature=0)\n",
        "tavily_tool = TavilySearchResults(max_results=5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7ee8707e1867"
      },
      "source": [
        "### Define prompt templates and Runnables"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "a09a6a6d1f36"
      },
      "outputs": [],
      "source": [
        "# Planning: Create an outline for the essay\n",
        "outline_template = ChatPromptTemplate.from_template(\n",
        "    \"Create a detailed outline for an essay on {topic}\"\n",
        ")\n",
        "\n",
        "\n",
        "# Research: Web search\n",
        "def research_fn(topic):\n",
        "    response = tavily_tool.invoke({\"query\": topic})\n",
        "    return \"\\n\".join([f\"- {result['content']}\" for result in response])\n",
        "\n",
        "\n",
        "# Writing: Write the essay based on outline and research\n",
        "writing_template = ChatPromptTemplate.from_template(\n",
        "    \"Based on the following outline and research, write a 3-paragraph essay on '{topic}':\\n\\nOutline:\\n{outline}\\n\\nResearch:\\n{research}\\n\\nEssay:\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9a18006523f7"
      },
      "source": [
        "### Define the Runnable Chain using [LangChain Expression Language (LCEL)](https://python.langchain.com/docs/how_to/#langchain-expression-language-lcel)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cf48601613fd"
      },
      "outputs": [],
      "source": [
        "# Define individual chains\n",
        "outline_chain = LLMChain(llm=model, prompt=outline_template)\n",
        "writing_chain = LLMChain(llm=model, prompt=writing_template)\n",
        "\n",
        "# Use the pipe operator to combine chains\n",
        "chain = (\n",
        "    outline_chain\n",
        "    | (\n",
        "        lambda result: {\n",
        "            \"topic\": result[\"topic\"],\n",
        "            \"outline\": result[\"text\"],\n",
        "            \"research\": research_fn(result[\"topic\"]),\n",
        "        }\n",
        "    )\n",
        "    | writing_chain\n",
        "    | (lambda result: result[\"text\"])  # Extract the essay text from the final result\n",
        "    | StrOutputParser()\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "839fc48dd408"
      },
      "source": [
        "### Generate the essay"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "a76f80ceec98"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "As climate change continues to fuel warmer ocean temperatures, the threat of increasingly powerful and frequent hurricanes looms large. Understanding the potential impacts of these storms is crucial for effective preparation and mitigation efforts. In late September and early October of 2024, Florida was struck by two such storms: Hurricane Helene, a Category 3 storm, and Hurricane Milton, a Category 1 storm. While both hurricanes brought destruction, their differing intensities and paths resulted in distinct impacts, ranging from widespread wastewater contamination to significant infrastructural damage and economic disruption.\n",
              "\n",
              "Hurricane Helene, the stronger of the two, caused significant environmental damage in Florida. St. Petersburg's infrastructure was overwhelmed, leading to the discharge of approximately 1.5 million gallons of untreated wastewater into the surrounding areas. The Glendale Wastewater Reclamation Facility in Lakeland, operating since 1926, experienced two major spills totaling five million gallons. This contamination posed a serious threat to public health and the delicate ecosystems of the Tampa Bay area. The coastal region experienced increased rainfall, which climate models indicated was increased in both likelihood and intensity.\n",
              "\n",
              "In contrast, Hurricane Milton, while weaker, inflicted substantial economic and infrastructural damage across Florida. Making landfall near Siesta Key as a Category 3 storm on October 9, 2024, Milton disrupted key industries and essential services. The fishing industry in Apalachicola Bay suffered greatly, with damage to boats, docks, and processing facilities leading to significant income loss for local fishermen. Debris removal and cleanup efforts were extensive, and the combined impact of Helene and Milton contributed to the ten costliest climate disasters of 2024, which caused more than $229 billion in damages globally. World Vision, through its 20 church partnerships, served over 39,600 people in Florida, Georgia, and the Carolinas in response to the hurricanes.\n",
              "\n",
              "While both hypothetical hurricanes brought destruction, Helene's impact was primarily focused on environmental contamination, while Milton caused significant economic disruption and infrastructure damage. As the threat of increasingly intense hurricanes continues to grow, proactive measures to enhance preparedness, strengthen infrastructure, and foster community resilience are essential to minimize the devastating impacts of these powerful storms. The events of late September and early October 2024 serve as a stark reminder of the urgent need for continued research, investment in resilient infrastructure, and community-based preparedness initiatives to mitigate the impacts of future hurricanes.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "essay = chain.invoke({\"topic\": prompt})\n",
        "display(Markdown(essay))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "294d3b7c43b2"
      },
      "source": [
        "## Generating Essays Using an Iterative, AI-Agent Approach with LangGraph\n",
        "\n",
        "This section demonstrates how to build a [LangGraph](https://langchain-ai.github.io/langgraph/)-powered AI agent to generate, revise, and critique essays using large language models such as Google's [Gemini API in Google AI Studio](https://ai.google.dev/gemini-api/docs) or the [Gemini API in Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/overview). The LangGraph code was adapted from the awesome DeepLearning.AI course on [AI Agents in LangGraph](https://www.deeplearning.ai/short-courses/ai-agents-in-langgraph/).\n",
        "\n",
        "By defining a structured state flow with nodes such as \"Planner,\" \"Research Plan,\" \"Generate,\" \"Reflect,\" and \"Research Critique,\" the system iteratively creates an essay on a given topic, incorporates feedback, and provides research-backed insights.\n",
        "\n",
        "<img src=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/workshops/ai-agents/3-langgraph-essay.png?raw=1\" width=\"900px\">\n",
        "\n",
        "The workflow enables automated essay generation with revision controls, making it ideal for structured writing tasks or educational use cases. Additionally, the notebook uses external search tools to gather and integrate real-time information into the essay content."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f8e41763086f"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "52fbe2cb7be7"
      },
      "outputs": [],
      "source": [
        "from typing import TypedDict\n",
        "\n",
        "# Common libraries\n",
        "from IPython.display import Image, Markdown, display\n",
        "\n",
        "# LangChain and LangGraph components\n",
        "from langchain_core.messages import HumanMessage, SystemMessage\n",
        "\n",
        "# LangChain integrations for Gemini API in Google AI Studio and Vertex AI\n",
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "from langchain_google_vertexai import ChatVertexAI\n",
        "from langgraph.checkpoint.memory import MemorySaver\n",
        "from langgraph.graph import END, StateGraph\n",
        "\n",
        "# Typing utilities for data validation and schema definitions\n",
        "from pydantic.v1 import BaseModel\n",
        "\n",
        "# Tavily client for performing web searches\n",
        "from tavily import TavilyClient"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fc6ae1fac44f"
      },
      "source": [
        "### Initialize agent memory, agent state, and schema for search queries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {
        "id": "6b92f7bab46d"
      },
      "outputs": [],
      "source": [
        "# Initialize agent memory\n",
        "memory = MemorySaver()\n",
        "\n",
        "\n",
        "# Define the agent's state\n",
        "class AgentState(TypedDict):\n",
        "    task: str\n",
        "    plan: str\n",
        "    draft: str\n",
        "    critique: str\n",
        "    content: list[str]\n",
        "    revision_number: int\n",
        "    max_revisions: int\n",
        "\n",
        "\n",
        "# Define a schema for search queries\n",
        "class Queries(BaseModel):\n",
        "    \"\"\"Variants of query to search for\"\"\"\n",
        "\n",
        "    queries: list[str]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d9660e58afab"
      },
      "source": [
        "### Initialize Gemini model and search tool\n",
        "\n",
        "Remember to set the environment variables `GOOGLE_API_KEY` and `TAVILY_API_KEY`. And configure credentials for Vertex AI if you switch to it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "id": "ec96b00bb67f"
      },
      "outputs": [],
      "source": [
        "if client.vertexai:\n",
        "    model = ChatVertexAI(project=PROJECT_ID, model=MODEL_ID, temperature=0)\n",
        "else:\n",
        "    model = ChatGoogleGenerativeAI(model=MODEL_ID, temperature=0)\n",
        "\n",
        "# Initialize Tavily client for performing web searches\n",
        "tavily = TavilyClient()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d94dc64d3846"
      },
      "source": [
        "### Define prompt templates for each stage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "metadata": {
        "id": "2cc6f9b05d29"
      },
      "outputs": [],
      "source": [
        "PLAN_PROMPT = \"\"\"You are an expert writer tasked with writing a high level outline of an essay.\n",
        "Write such an outline for the user provided topic. Give an outline of the essay along with any\n",
        "relevant notes or instructions for the sections.\"\"\"\n",
        "\n",
        "WRITER_PROMPT = \"\"\"You are an essay assistant tasked with writing excellent 3-paragraph essays.\n",
        "Generate the best essay possible for the user's request and the initial outline.\n",
        "If the user provides critique, respond with a revised version of your previous attempts.\n",
        "Use Markdown formatting to specify a title and section headers for each paragraph.\n",
        "Utilize all of the information below as needed:\n",
        "---\n",
        "{content}\"\"\"\n",
        "\n",
        "REFLECTION_PROMPT = \"\"\"You are a teacher grading an essay submission.\n",
        "Generate critique and recommendations for the user's submission.\n",
        "Provide detailed recommendations, including requests for length, depth, style, etc.\"\"\"\n",
        "\n",
        "RESEARCH_PLAN_PROMPT = \"\"\"You are a researcher charged with providing information that can\n",
        "be used when writing the following essay. Generate a list of search queries that will gather\n",
        "any relevant information. Only generate 3 queries max.\"\"\"\n",
        "\n",
        "RESEARCH_CRITIQUE_PROMPT = \"\"\"You are a researcher charged with providing information that can\n",
        "be used when making any requested revisions (as outlined below).\n",
        "Generate a list of search queries that will gather any relevant information.\n",
        "Only generate 3 queries max.\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c4f51c668222"
      },
      "source": [
        "### Define node functions for each stage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "metadata": {
        "id": "75c8d7021369"
      },
      "outputs": [],
      "source": [
        "# Generate an outline for the essay\n",
        "\n",
        "\n",
        "def plan_node(state: AgentState):\n",
        "    messages = [SystemMessage(content=PLAN_PROMPT), HumanMessage(content=state[\"task\"])]\n",
        "    response = model.invoke(messages)\n",
        "    return {\"plan\": response.content}\n",
        "\n",
        "\n",
        "# Conducts research based on the generated plan and web search results\n",
        "def research_plan_node(state: AgentState):\n",
        "    queries = model.with_structured_output(Queries).invoke(\n",
        "        [\n",
        "            SystemMessage(content=RESEARCH_PLAN_PROMPT),\n",
        "            HumanMessage(content=state[\"task\"]),\n",
        "        ]\n",
        "    )\n",
        "    content = state[\"content\"] or []\n",
        "    for q in queries.queries:\n",
        "        response = tavily.search(query=q, max_results=2)\n",
        "        for r in response[\"results\"]:\n",
        "            content.append(r[\"content\"])\n",
        "    return {\"content\": content}\n",
        "\n",
        "\n",
        "# Generates a draft based on the content and plan\n",
        "def generation_node(state: AgentState):\n",
        "    content = \"\\n\\n\".join(state[\"content\"] or [])\n",
        "    user_message = HumanMessage(\n",
        "        content=f\"{state['task']}\\n\\nHere is my plan:\\n\\n{state['plan']}\"\n",
        "    )\n",
        "    messages = [\n",
        "        SystemMessage(content=WRITER_PROMPT.format(content=content)),\n",
        "        user_message,\n",
        "    ]\n",
        "    response = model.invoke(messages)\n",
        "    return {\n",
        "        \"draft\": response.content,\n",
        "        \"revision_number\": state.get(\"revision_number\", 1) + 1,\n",
        "    }\n",
        "\n",
        "\n",
        "# Provides feedback or critique on the draft\n",
        "def reflection_node(state: AgentState):\n",
        "    messages = [\n",
        "        SystemMessage(content=REFLECTION_PROMPT),\n",
        "        HumanMessage(content=state[\"draft\"]),\n",
        "    ]\n",
        "    response = model.invoke(messages)\n",
        "    return {\"critique\": response.content}\n",
        "\n",
        "\n",
        "# Conducts research based on the critique\n",
        "def research_critique_node(state: AgentState):\n",
        "    queries = model.with_structured_output(Queries).invoke(\n",
        "        [\n",
        "            SystemMessage(content=RESEARCH_CRITIQUE_PROMPT),\n",
        "            HumanMessage(content=state[\"critique\"]),\n",
        "        ]\n",
        "    )\n",
        "    content = state[\"content\"] or []\n",
        "    for q in queries.queries:\n",
        "        response = tavily.search(query=q, max_results=2)\n",
        "        for r in response[\"results\"]:\n",
        "            content.append(r[\"content\"])\n",
        "    return {\"content\": content}\n",
        "\n",
        "\n",
        "# Determines whether the critique and research cycle should\n",
        "# continue based on the number of revisions\n",
        "def should_continue(state):\n",
        "    if state[\"revision_number\"] > state[\"max_revisions\"]:\n",
        "        return END\n",
        "    return \"reflect\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "48569416595a"
      },
      "source": [
        "### Define and compile the graph"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "metadata": {
        "id": "86567ad87aa2"
      },
      "outputs": [],
      "source": [
        "# Initialize the state graph\n",
        "builder = StateGraph(AgentState)\n",
        "\n",
        "# Add nodes for each step in the workflow\n",
        "builder.add_node(\"planner\", plan_node)\n",
        "builder.add_node(\"generate\", generation_node)\n",
        "builder.add_node(\"reflect\", reflection_node)\n",
        "builder.add_node(\"research_plan\", research_plan_node)\n",
        "builder.add_node(\"research_critique\", research_critique_node)\n",
        "\n",
        "# Set the entry point of the workflow\n",
        "builder.set_entry_point(\"planner\")\n",
        "\n",
        "# Add conditional edges for task continuation or end\n",
        "builder.add_conditional_edges(\n",
        "    \"generate\", should_continue, {END: END, \"reflect\": \"reflect\"}\n",
        ")\n",
        "\n",
        "# Define task sequence edges\n",
        "builder.add_edge(\"planner\", \"research_plan\")\n",
        "builder.add_edge(\"research_plan\", \"generate\")\n",
        "\n",
        "builder.add_edge(\"reflect\", \"research_critique\")\n",
        "builder.add_edge(\"research_critique\", \"generate\")\n",
        "\n",
        "# Compile the graph with memory state management\n",
        "graph = builder.compile(checkpointer=memory)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "44d87b0a2052"
      },
      "source": [
        "### Show the compiled graph"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9c3170874384"
      },
      "outputs": [],
      "source": [
        "Image(graph.get_graph().draw_mermaid_png())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c95bebc7e74c"
      },
      "source": [
        "### Run the agent - write on!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 30,
      "metadata": {
        "id": "2a849843b454"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# planner"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Okay, here's a high-level outline for an essay exploring the impacts of Hurricanes Helene and Milton in 2024. This outline focuses on providing a structure for a comprehensive analysis, considering various sectors and potential long-term consequences.\n",
              "\n",
              "**Essay Title (Example):**  Twin Storms, Lasting Scars: A Comparative Analysis of the Impacts of Hurricanes Helene and Milton (2024)\n",
              "\n",
              "**I. Introduction**\n",
              "\n",
              "*   **Hook:** Start with a compelling statistic or anecdote about the 2024 hurricane season or the general increase in extreme weather events.\n",
              "*   **Background:** Briefly introduce Hurricane Helene and Hurricane Milton, including their formation, paths, and peak intensities. Mention the geographical areas most affected by each storm.\n",
              "*   **Thesis Statement:**  Clearly state the essay's main argument.  For example: \"While both Hurricanes Helene and Milton caused significant damage in 2024, their impacts differed substantially due to variations in intensity, geographical location, and pre-existing vulnerabilities, resulting in distinct challenges for affected communities in terms of infrastructure, economy, and public health.\"\n",
              "*   **Roadmap:** Briefly outline the key areas the essay will cover (e.g., infrastructure damage, economic consequences, environmental effects, and social impacts).\n",
              "\n",
              "**II. Hurricane Helene: Impacts and Analysis**\n",
              "\n",
              "*   **A. Geographical Context and Vulnerabilities:**\n",
              "    *   Describe the specific regions affected by Hurricane Helene.\n",
              "    *   Analyze the pre-existing vulnerabilities of these regions (e.g., coastal erosion, poverty, inadequate infrastructure, reliance on specific industries).\n",
              "    *   Discuss any evacuation efforts and their effectiveness.\n",
              "*   **B. Infrastructure Damage:**\n",
              "    *   Detail the damage to critical infrastructure: power grids, transportation networks (roads, bridges, ports), communication systems, water and sanitation facilities.\n",
              "    *   Provide specific examples and, if available, estimated costs of repair.\n",
              "    *   Discuss the immediate and long-term consequences of infrastructure failure (e.g., power outages, disruptions to supply chains).\n",
              "*   **C. Economic Consequences:**\n",
              "    *   Analyze the impact on key industries in the affected regions (e.g., tourism, agriculture, fishing).\n",
              "    *   Discuss job losses, business closures, and disruptions to trade.\n",
              "    *   Examine the role of insurance and disaster relief in mitigating economic losses.\n",
              "*   **D. Environmental Effects:**\n",
              "    *   Assess the environmental damage caused by Helene: coastal erosion, flooding, saltwater intrusion, damage to ecosystems (e.g., wetlands, coral reefs).\n",
              "    *   Discuss the potential long-term ecological consequences.\n",
              "*   **E. Social Impacts:**\n",
              "    *   Examine the impact on public health: injuries, disease outbreaks, mental health issues.\n",
              "    *   Discuss displacement, homelessness, and food insecurity.\n",
              "    *   Analyze the role of community organizations and government agencies in providing aid and support.\n",
              "\n",
              "**III. Hurricane Milton: Impacts and Analysis**\n",
              "\n",
              "*   **A. Geographical Context and Vulnerabilities:**\n",
              "    *   Describe the specific regions affected by Hurricane Milton.\n",
              "    *   Analyze the pre-existing vulnerabilities of these regions (e.g., different demographics, building codes, economic activities compared to Helene's affected areas).\n",
              "    *   Discuss any evacuation efforts and their effectiveness.\n",
              "*   **B. Infrastructure Damage:**\n",
              "    *   Detail the damage to critical infrastructure, noting any differences from the types of damage caused by Helene.\n",
              "    *   Provide specific examples and estimated costs of repair.\n",
              "    *   Discuss the immediate and long-term consequences of infrastructure failure.\n",
              "*   **C. Economic Consequences:**\n",
              "    *   Analyze the impact on key industries in the affected regions, noting any differences from Helene's affected areas.\n",
              "    *   Discuss job losses, business closures, and disruptions to trade.\n",
              "    *   Examine the role of insurance and disaster relief in mitigating economic losses.\n",
              "*   **D. Environmental Effects:**\n",
              "    *   Assess the environmental damage caused by Milton, noting any differences from Helene.\n",
              "    *   Discuss the potential long-term ecological consequences.\n",
              "*   **E. Social Impacts:**\n",
              "    *   Examine the impact on public health, noting any differences from Helene's affected areas.\n",
              "    *   Discuss displacement, homelessness, and food insecurity.\n",
              "    *   Analyze the role of community organizations and government agencies in providing aid and support.\n",
              "\n",
              "**IV. Comparative Analysis: Helene vs. Milton**\n",
              "\n",
              "*   **A. Key Differences in Impacts:**\n",
              "    *   Directly compare and contrast the impacts of the two hurricanes across the categories discussed above (infrastructure, economy, environment, social).\n",
              "    *   Highlight the factors that contributed to these differences (e.g., storm intensity, geographical characteristics, preparedness levels).\n",
              "*   **B. Lessons Learned:**\n",
              "    *   Identify key lessons learned from the responses to both hurricanes.\n",
              "    *   Discuss the effectiveness of different mitigation and adaptation strategies.\n",
              "    *   Consider the implications for future hurricane preparedness and disaster management.\n",
              "\n",
              "**V. Conclusion**\n",
              "\n",
              "*   **Restate Thesis:** Summarize the main argument of the essay, emphasizing the distinct impacts of the two hurricanes.\n",
              "*   **Broader Implications:** Discuss the broader implications of these events in the context of climate change and increasing hurricane intensity.\n",
              "*   **Call to Action (Optional):** Suggest potential actions that can be taken to improve hurricane preparedness, resilience, and disaster response in the future.\n",
              "*   **Concluding Thought:** End with a powerful statement about the challenges posed by hurricanes and the importance of proactive measures to protect vulnerable communities.\n",
              "\n",
              "**Important Notes:**\n",
              "\n",
              "*   **Sources:**  Use credible sources, including government reports (e.g., NOAA, FEMA), academic studies, news articles from reputable sources, and reports from NGOs involved in disaster relief.\n",
              "*   **Data:**  Include specific data and statistics to support your claims (e.g., rainfall amounts, wind speeds, damage estimates, number of people displaced).\n",
              "*   **Visuals:** Consider including maps, charts, and photographs to enhance the essay.\n",
              "*   **Objectivity:**  Present a balanced and objective analysis, avoiding sensationalism or biased reporting.\n",
              "*   **Future Projections:** While focusing on the 2024 events, briefly touch upon how climate change might influence future hurricane seasons and the need for long-term adaptation strategies.\n",
              "*   **Specificity:** The more specific you can be about the locations affected and the types of damage, the stronger your essay will be.\n",
              "\n",
              "This outline provides a solid framework. Remember to adapt it based on the specific information available about Hurricanes Helene and Milton in 2024. Good luck!\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "# research_plan"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "North Carolina was severely impacted by Hurricane Helene during late September 2024, primarily in its western Appalachian region, causing at least 105 reported deaths and significant destruction of infrastructure and residential areas across several settlements.[1] After making landfall in the Big Bend region of Florida on September 27, the hurricane began to traverse over land across Georgia as a Category 2 hurricane and into the Appalachian mountain range as a tropical storm, depositing record-breaking amounts of rainfall across several settlements in western North Carolina, such as Asheville, Swannanoa, Spruce Pine, Chimney Rock, Montreat, Lake Lure, and several others. Of the 241 people reported victims of Hurricane Helene in the United States, 119 people were in North Carolina, surpassing the state record of 80 deaths recorded in a 1916 flood.[8][35] Of these, 72 residents of Buncombe County were among the deceased."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Ask the Chatbot Games & Quizzes History & Society Science & Tech Biographies Animals & Nature Geography & Travel Arts & Culture ProCon Money Videos Hurricane Helene, large, catastrophic tropical cyclone notable for its rapid intensification that ultimately produced a wide swath of damage and loss of life that extended from northwestern Florida, where the storm made landfall on September 26, 2024, to Tennessee, Georgia, and North Carolina. Although Helene’s winds had diminished to tropical-storm strength, the storm delivered a broad and deadly swath of heavy rain across the southeastern U.S. In parts of Florida, Georgia, North and South Carolina, Tennessee, and Virginia, record rainfall caused rivers to overflow and produced flash flooding, road washouts, and even landslides in some areas."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "An EF-0 tornado impacted Martin and St. Lucie counties on October 9, 2024, as Hurricane Milton's rainbands swept across the Treasure Coast. An EF-1 tornado impacted St. Lucie County on October 9, 2024, as Hurricane Milton's outer rainbands moved across the Treasure Coast. In Fort Pierce, the tornado caused significant structural damage to a metal canopy at the St. Lucie County Sheriff's Office, with peak winds estimated at 90 mph before weakening and lifting near the I-95 and Okeechobee interchange. An EF-1 tornado touched down near the Belcher Canal in Fort Pierce, causing vegetative damage and partial roof loss near St. Lucie Blvd and N 25th St. The tornado continued northwest across Treasure Coast International Airport, where several small planes were tossed and recorded gusts of 60 mph."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "A tropical storm watch was issued for Extreme Northwest Bahamian Islands on October 8, 2024, upgraded six hours later to a tropical storm warning.[102][103][104] Grand Bahama activated their emergency operations center.[105] The Royal Bahamas Defence Force went on standby with supplies prepared for Hurricane Milton.[106] In-person schools on Grand Bahama, Bimini, Abaco, and Grand Cay were closed.[107] The Anglican Central Education Authority closed two campuses.[108] Bahamian students in Florida were ordered to evacuate; Bahamasair made two flights on October 7 and 8 to Orlando.[109] The Grand Bahama International Airport had closed.[110] Bahamas Power and Light offices in northern islands closed October 9.[111] Banks on Grand Bahama and Abaco closed October 10.[112] A large surge in sales of hurricane-related supplies occurred.[105] ^ Hurricane Milton Spawned Record Number Of Florida Tornadoes, The Weather Channel, October 23, 2024"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Search for News Email This Subscribe to Newsletter Email to a friend Facebook Tweet LinkedIn Print Article The 2024 hurricane season presented challenges for insurers thanks largely to hurricanes Beryl, Helene, and Milton—the three powerful storms caused more than $138 billion in damage as well as $52 million in insured losses. Hurricane Milton insured losses totaled $25 billion with a total loss of $38 billion. The company analyzed 2 million properties in the area of where Hurricane Helene hit the southeastern area, finding: 131,004 properties were impacted, 43,352 properties suffered severe damage and 3,580 properties were destroyed. Get the latest insurance news Email This Subscribe to Newsletter Email to a friend Facebook Tweet LinkedIn Print Article Email * More News More News Features Claims News Email Newsletters"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Helene, Milton losses expected to surpass \"truly historic\" $50 billion each - CBS News Monstrous hurricanes Helene and Milton caused so much complex havoc that damages are still being added up, but government and private experts say they will likely join the infamous ranks of Katrina, Sandy and Harvey as super costly $50-billion-plus killers. But even adjusted for inflation, damages from intense storms are skyrocketing because people are building in harm's way, rebuilding costs are rising faster than inflation and human-caused climate change are making storms stronger and wetter, experts in different fields said. Of the top 10 costliest hurricanes as compiled by insurance giant Swiss Re - not including Helene or Milton yet - insured damage is about 44% of total costs."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "# generate"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Okay, I will write a 3-paragraph essay based on the information provided.\n",
              "\n",
              "**Title: The Destructive Force of Hurricanes Helene and Milton in 2024**\n",
              "\n",
              "**Paragraph 1: Introduction to the 2024 Hurricane Season**\n",
              "\n",
              "The 2024 hurricane season proved to be particularly devastating, marked by the significant impacts of Hurricanes Helene and Milton. These storms left a trail of destruction across multiple states, causing billions of dollars in damage and resulting in tragic loss of life. Hurricane Helene, notable for its rapid intensification, made landfall in Florida before traversing through Georgia and into the Appalachian region, unleashing record-breaking rainfall and widespread flooding. Meanwhile, Hurricane Milton spawned a record number of tornadoes in Florida, exacerbating the damage caused by high winds and heavy rain. The combined impact of these storms presented unprecedented challenges for insurers and communities alike, underscoring the increasing vulnerability of coastal and inland regions to extreme weather events.\n",
              "\n",
              "**Paragraph 2: Contrasting Impacts of Helene and Milton**\n",
              "\n",
              "While both hurricanes inflicted substantial damage, their impacts varied significantly due to differences in their paths and intensities. Hurricane Helene's slow movement and torrential rainfall led to catastrophic flooding in the Appalachian region, particularly in western North Carolina, where it caused a state-record number of fatalities. The storm's impact extended beyond immediate property damage, disrupting critical infrastructure such as power grids and transportation networks, hindering rescue and recovery efforts. In contrast, Hurricane Milton's primary impact was felt in Florida, where it spawned numerous tornadoes that caused structural damage to buildings and infrastructure. The storm's effects were further compounded by insured losses totaling $25 billion, contributing to a total loss of $38 billion.\n",
              "\n",
              "**Paragraph 3: Long-Term Consequences and Lessons Learned**\n",
              "\n",
              "The aftermath of Hurricanes Helene and Milton has prompted a comprehensive reassessment of hurricane preparedness and disaster management strategies. The extensive damage caused by these storms has highlighted the need for improved infrastructure resilience, enhanced early warning systems, and more effective evacuation plans. Moreover, the economic consequences of the hurricanes have underscored the importance of insurance coverage and disaster relief programs in mitigating financial losses for affected communities. As climate change continues to intensify extreme weather events, it is imperative that proactive measures are taken to protect vulnerable populations and build more resilient communities capable of withstanding the destructive force of future hurricanes.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "**Revision Number**: 2"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "# reflect"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Okay, here's a critique of your 3-paragraph essay, \"The Destructive Force of Hurricanes Helene and Milton in 2024,\" along with recommendations for improvement.\n",
              "\n",
              "**Overall Impression:**\n",
              "\n",
              "The essay provides a decent overview of the hypothetical impact of Hurricanes Helene and Milton in 2024. It touches upon key aspects like the damage caused, contrasting impacts, and long-term consequences. However, it lacks depth, specific examples, and a compelling narrative. The language is somewhat generic and could be more engaging.\n",
              "\n",
              "**Specific Feedback and Recommendations:**\n",
              "\n",
              "**Paragraph 1: Introduction**\n",
              "\n",
              "*   **Specificity:** While you mention the storms caused billions in damage and loss of life, these statements lack impact without specific numbers or examples. *Recommendation: Add estimated death tolls (even if hypothetical), specific dollar amounts for damage in each state, and perhaps a brief, impactful anecdote about a family affected by one of the storms.*\n",
              "*   **Intensification:** You mention Helene's rapid intensification. *Recommendation: Briefly explain what factors contributed to this rapid intensification (e.g., warm water temperatures, favorable atmospheric conditions). This adds a layer of scientific understanding.*\n",
              "*   **Tornadoes:** You mention Milton spawned a record number of tornadoes. *Recommendation: Quantify this \"record number.\" How many tornadoes? Where were they concentrated? What was the strongest tornado's rating (e.g., EF3)?*\n",
              "*   **\"Unprecedented challenges for insurers\":** This is a bit vague. *Recommendation: Elaborate. What specific challenges did insurers face? Were there issues with payouts, policy coverage, or reinsurance?*\n",
              "*   **Length:** This paragraph is a good length, but the added details will likely make it a bit longer, which is fine.\n",
              "\n",
              "**Paragraph 2: Contrasting Impacts**\n",
              "\n",
              "*   **Depth:** The contrast between the storms is a good idea, but it needs more development. *Recommendation: Instead of just saying Helene caused flooding, describe the flooding. What areas were submerged? How high did the water get? What infrastructure was affected (e.g., bridges washed out, dams breached)? For Milton, describe the types of structural damage caused by the tornadoes (e.g., homes flattened, businesses destroyed).*\n",
              "*   **Human Element:** The essay is very focused on infrastructure and economic damage. *Recommendation: Include a sentence or two about the human impact of each storm. For example, mention the displacement of residents, the challenges faced by first responders, or the emotional toll on affected communities.*\n",
              "*   **\"State-record number of fatalities\":** Again, be specific. *Recommendation: Provide the actual number of fatalities.*\n",
              "*   **Dollar Amounts:** You mention insured losses and total losses. *Recommendation: Clarify the difference between these figures. What accounts for the $13 billion difference between insured and total losses?*\n",
              "*   **Length:** This paragraph could benefit from being slightly longer to accommodate the added details.\n",
              "\n",
              "**Paragraph 3: Long-Term Consequences and Lessons Learned**\n",
              "\n",
              "*   **Specificity:** \"Improved infrastructure resilience\" and \"enhanced early warning systems\" are broad terms. *Recommendation: Provide concrete examples. What specific infrastructure improvements are needed (e.g., elevating homes, building stronger levees, upgrading power grids)? How can early warning systems be enhanced (e.g., more weather stations, better communication strategies)?*\n",
              "*   **Evacuation Plans:** *Recommendation: What made the evacuation plans ineffective? Were there traffic problems, lack of transportation, or communication breakdowns?*\n",
              "*   **Insurance Coverage:** *Recommendation: Were there specific issues with insurance coverage that were revealed by these storms (e.g., underinsurance, exclusions for flood damage)?*\n",
              "*   **Climate Change Connection:** While mentioning climate change is good, make the connection more explicit. *Recommendation: Explain how climate change is contributing to the intensification of hurricanes and the increased frequency of extreme weather events. Cite a credible source (even a hypothetical one for 2024) to support this claim.*\n",
              "*   **Call to Action:** Consider ending with a stronger call to action. *Recommendation: Instead of just saying \"proactive measures are taken,\" suggest specific actions that governments, communities, and individuals can take to prepare for future hurricanes.*\n",
              "*   **Length:** This paragraph is a good length, but the added details will likely make it a bit longer, which is fine.\n",
              "\n",
              "**Style and Tone:**\n",
              "\n",
              "*   **Engaging Language:** The writing is somewhat dry and factual. *Recommendation: Use more vivid language to describe the impact of the storms. For example, instead of saying \"widespread flooding,\" you could say \"floodwaters inundated entire neighborhoods, leaving homes submerged to their rooftops.\"*\n",
              "*   **Active Voice:** Use active voice whenever possible to make the writing more direct and impactful.\n",
              "*   **Conciseness:** Avoid unnecessary words and phrases.\n",
              "\n",
              "**Overall Length:**\n",
              "\n",
              "The essay is currently a good starting length. The added details and examples will naturally increase the length, making it more comprehensive and impactful. Aim for each paragraph to be approximately 7-10 sentences long.\n",
              "\n",
              "**Revised Structure Suggestion:**\n",
              "\n",
              "Consider restructuring the essay slightly to create a stronger narrative flow:\n",
              "\n",
              "1.  **Introduction:** (As is, but with added details as suggested above)\n",
              "2.  **Hurricane Helene: A Tale of Devastating Flooding:** (Focus solely on Helene's impact, with specific examples and human stories)\n",
              "3.  **Hurricane Milton: A Barrage of Tornadoes:** (Focus solely on Milton's impact, with specific examples and human stories)\n",
              "4.  **Lessons Learned and the Path Forward:** (Combine the current third paragraph with a stronger call to action)\n",
              "\n",
              "By dedicating a full paragraph to each storm, you can provide a more detailed and compelling account of their individual impacts.\n",
              "\n",
              "**In summary, to improve your essay, focus on adding specific details, examples, and a stronger narrative voice. Make the connection to climate change more explicit and end with a compelling call to action.** Good luck!\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "# research_critique"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "North Carolina was severely impacted by Hurricane Helene during late September 2024, primarily in its western Appalachian region, causing at least 105 reported deaths and significant destruction of infrastructure and residential areas across several settlements.[1] After making landfall in the Big Bend region of Florida on September 27, the hurricane began to traverse over land across Georgia as a Category 2 hurricane and into the Appalachian mountain range as a tropical storm, depositing record-breaking amounts of rainfall across several settlements in western North Carolina, such as Asheville, Swannanoa, Spruce Pine, Chimney Rock, Montreat, Lake Lure, and several others. Of the 241 people reported victims of Hurricane Helene in the United States, 119 people were in North Carolina, surpassing the state record of 80 deaths recorded in a 1916 flood.[8][35] Of these, 72 residents of Buncombe County were among the deceased."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Ask the Chatbot Games & Quizzes History & Society Science & Tech Biographies Animals & Nature Geography & Travel Arts & Culture ProCon Money Videos Hurricane Helene, large, catastrophic tropical cyclone notable for its rapid intensification that ultimately produced a wide swath of damage and loss of life that extended from northwestern Florida, where the storm made landfall on September 26, 2024, to Tennessee, Georgia, and North Carolina. Although Helene’s winds had diminished to tropical-storm strength, the storm delivered a broad and deadly swath of heavy rain across the southeastern U.S. In parts of Florida, Georgia, North and South Carolina, Tennessee, and Virginia, record rainfall caused rivers to overflow and produced flash flooding, road washouts, and even landslides in some areas."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "An EF-0 tornado impacted Martin and St. Lucie counties on October 9, 2024, as Hurricane Milton's rainbands swept across the Treasure Coast. An EF-1 tornado impacted St. Lucie County on October 9, 2024, as Hurricane Milton's outer rainbands moved across the Treasure Coast. In Fort Pierce, the tornado caused significant structural damage to a metal canopy at the St. Lucie County Sheriff's Office, with peak winds estimated at 90 mph before weakening and lifting near the I-95 and Okeechobee interchange. An EF-1 tornado touched down near the Belcher Canal in Fort Pierce, causing vegetative damage and partial roof loss near St. Lucie Blvd and N 25th St. The tornado continued northwest across Treasure Coast International Airport, where several small planes were tossed and recorded gusts of 60 mph."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "A tropical storm watch was issued for Extreme Northwest Bahamian Islands on October 8, 2024, upgraded six hours later to a tropical storm warning.[102][103][104] Grand Bahama activated their emergency operations center.[105] The Royal Bahamas Defence Force went on standby with supplies prepared for Hurricane Milton.[106] In-person schools on Grand Bahama, Bimini, Abaco, and Grand Cay were closed.[107] The Anglican Central Education Authority closed two campuses.[108] Bahamian students in Florida were ordered to evacuate; Bahamasair made two flights on October 7 and 8 to Orlando.[109] The Grand Bahama International Airport had closed.[110] Bahamas Power and Light offices in northern islands closed October 9.[111] Banks on Grand Bahama and Abaco closed October 10.[112] A large surge in sales of hurricane-related supplies occurred.[105] ^ Hurricane Milton Spawned Record Number Of Florida Tornadoes, The Weather Channel, October 23, 2024"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Search for News Email This Subscribe to Newsletter Email to a friend Facebook Tweet LinkedIn Print Article The 2024 hurricane season presented challenges for insurers thanks largely to hurricanes Beryl, Helene, and Milton—the three powerful storms caused more than $138 billion in damage as well as $52 million in insured losses. Hurricane Milton insured losses totaled $25 billion with a total loss of $38 billion. The company analyzed 2 million properties in the area of where Hurricane Helene hit the southeastern area, finding: 131,004 properties were impacted, 43,352 properties suffered severe damage and 3,580 properties were destroyed. Get the latest insurance news Email This Subscribe to Newsletter Email to a friend Facebook Tweet LinkedIn Print Article Email * More News More News Features Claims News Email Newsletters"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Helene, Milton losses expected to surpass \"truly historic\" $50 billion each - CBS News Monstrous hurricanes Helene and Milton caused so much complex havoc that damages are still being added up, but government and private experts say they will likely join the infamous ranks of Katrina, Sandy and Harvey as super costly $50-billion-plus killers. But even adjusted for inflation, damages from intense storms are skyrocketing because people are building in harm's way, rebuilding costs are rising faster than inflation and human-caused climate change are making storms stronger and wetter, experts in different fields said. Of the top 10 costliest hurricanes as compiled by insurance giant Swiss Re - not including Helene or Milton yet - insured damage is about 44% of total costs."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Hurricane Helene (/ hɛˈliːn / ⓘ heh-LEEN) [1] was a deadly and devastating tropical cyclone that caused widespread catastrophic damage and numerous fatalities across the Southeastern United States in late September 2024."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Ask the Chatbot Games & Quizzes History & Society Science & Tech Biographies Animals & Nature Geography & Travel Arts & Culture ProCon Money Videos Hurricane Helene, large, catastrophic tropical cyclone notable for its rapid intensification that ultimately produced a wide swath of damage and loss of life that extended from northwestern Florida, where the storm made landfall on September 26, 2024, to Tennessee, Georgia, and North Carolina. Although Helene’s winds had diminished to tropical-storm strength, the storm delivered a broad and deadly swath of heavy rain across the southeastern U.S. In parts of Florida, Georgia, North and South Carolina, Tennessee, and Virginia, record rainfall caused rivers to overflow and produced flash flooding, road washouts, and even landslides in some areas."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "An EF-0 tornado impacted Martin and St. Lucie counties on October 9, 2024, as Hurricane Milton's rainbands swept across the Treasure Coast. An EF-1 tornado impacted St. Lucie County on October 9, 2024, as Hurricane Milton's outer rainbands moved across the Treasure Coast. In Fort Pierce, the tornado caused significant structural damage to a metal canopy at the St. Lucie County Sheriff's Office, with peak winds estimated at 90 mph before weakening and lifting near the I-95 and Okeechobee interchange. An EF-1 tornado touched down near the Belcher Canal in Fort Pierce, causing vegetative damage and partial roof loss near St. Lucie Blvd and N 25th St. The tornado continued northwest across Treasure Coast International Airport, where several small planes were tossed and recorded gusts of 60 mph."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "A destroyed house is seen in Lakewood Park, Florida, after a tornado hit the area and caused severe damage as Hurricane Milton swept through Florida on Oct. 10, 2024. (GIORGIO VIERA/AFP via Getty"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Climate change caused the maximum wind speeds generated by roughly 80% of Atlantic Basin hurricanes from 2019 and 2023 to intensify by an average of 18 miles per hour, according to a new Climate Central study published in Environmental Research: Climate. Alongside this peer-reviewed study, Climate Central published a report, Climate change increased wind speeds for every 2024 Atlantic hurricane, expanding the framework to the 2024 Atlantic Basin hurricane season. Read Climate Central’s full report: Climate change increased wind speeds for every 2024 Atlantic hurricane. Climate Central’s Climate Shift Index: Ocean measures the influence of climate change on daily ocean temperatures and helps connect human-caused ocean warming to consequences, such as hurricane rapid intensification."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "All eleven hurricanes in 2024 (as of November 10) intensified by 9-28 mph during the record-breaking ocean warmth of the 2024 hurricane season, strengthening over waters made as much as 2.5°F"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "# generate"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "Okay, I will use your outline to generate a 3-paragraph essay.\n",
              "\n",
              "**Title: The Destructive Wake of Hurricanes Helene and Milton in 2024**\n",
              "\n",
              "**Paragraph 1: Introduction to the 2024 Hurricane Season**\n",
              "\n",
              "The 2024 hurricane season proved to be a stark reminder of the increasing intensity and devastating potential of tropical cyclones, with Hurricanes Helene and Milton leaving a trail of destruction across the Southeastern United States. Helene, a large and catastrophic storm, made landfall in Florida before cutting a deadly path through Georgia and into the Appalachian region, while Milton impacted the Treasure Coast of Florida. Although both storms brought widespread damage, their impacts differed significantly due to variations in their tracks, intensities, and the vulnerabilities of the affected regions. This essay will explore the distinct consequences of Hurricanes Helene and Milton, highlighting the challenges faced by impacted communities in terms of infrastructure, economic stability, and overall resilience.\n",
              "\n",
              "**Paragraph 2: Contrasting Impacts of Helene and Milton**\n",
              "\n",
              "Hurricane Helene's impact was most acutely felt in the Appalachian region of North Carolina, where record-breaking rainfall led to catastrophic flooding and landslides. The storm claimed over 100 lives in the state and caused extensive damage to infrastructure, isolating communities and disrupting essential services. In contrast, Hurricane Milton, while less deadly, spawned a series of tornadoes in Florida, causing significant structural damage and disrupting air travel. The economic consequences also varied, with Helene severely impacting tourism and agriculture in the Appalachian region, while Milton primarily affected coastal communities and infrastructure in Florida. The differing impacts underscore the importance of considering the specific vulnerabilities of each region when preparing for and responding to hurricanes.\n",
              "\n",
              "**Paragraph 3: Lessons Learned and the Future of Hurricane Preparedness**\n",
              "\n",
              "The experiences of Hurricanes Helene and Milton in 2024 offer valuable lessons for future hurricane preparedness and disaster management. The need for resilient infrastructure, effective evacuation plans, and coordinated disaster relief efforts was evident in both cases. Furthermore, the increasing intensity of these storms highlights the urgent need to address climate change and its contribution to extreme weather events. By understanding the distinct impacts of these hurricanes and investing in proactive measures, communities can better protect themselves from the devastating consequences of future storms.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "**Revision Number**: 3"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "---\n",
            "\n"
          ]
        }
      ],
      "source": [
        "# Define the topic of the essay\n",
        "ESSAY_TOPIC = \"What were the impacts of Hurricane Helene and Hurricane Milton in 2024?\"\n",
        "\n",
        "# Define a thread configuration with a unique thread ID\n",
        "thread = {\"configurable\": {\"thread_id\": \"1\"}}\n",
        "\n",
        "# Stream through the graph execution with an initial task and state\n",
        "for s in graph.stream(\n",
        "    {\n",
        "        \"task\": ESSAY_TOPIC,  # Initial task\n",
        "        \"max_revisions\": 2,  # Maximum number of revisions allowed\n",
        "        \"revision_number\": 1,  # Current revision number\n",
        "        \"content\": [],  # Initial empty content list\n",
        "    },\n",
        "    thread,\n",
        "):\n",
        "    step = next(iter(s))\n",
        "    display(Markdown(f\"# {step}\"))\n",
        "    for key, content in s[step].items():\n",
        "        if key == \"revision_number\":\n",
        "            display(Markdown(f\"**Revision Number**: {content}\"))\n",
        "        elif isinstance(content, list):\n",
        "            for c in content:\n",
        "                display(Markdown(c))\n",
        "        else:\n",
        "            display(Markdown(content))\n",
        "    print(\"\\n---\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4c95d0cd7f6a"
      },
      "source": [
        "### Output the final draft of the essay"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 31,
      "metadata": {
        "id": "e50e674081f2"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Okay, I will use your outline to generate a 3-paragraph essay.\n",
              "\n",
              "**Title: The Destructive Wake of Hurricanes Helene and Milton in 2024**\n",
              "\n",
              "**Paragraph 1: Introduction to the 2024 Hurricane Season**\n",
              "\n",
              "The 2024 hurricane season proved to be a stark reminder of the increasing intensity and devastating potential of tropical cyclones, with Hurricanes Helene and Milton leaving a trail of destruction across the Southeastern United States. Helene, a large and catastrophic storm, made landfall in Florida before cutting a deadly path through Georgia and into the Appalachian region, while Milton impacted the Treasure Coast of Florida. Although both storms brought widespread damage, their impacts differed significantly due to variations in their tracks, intensities, and the vulnerabilities of the affected regions. This essay will explore the distinct consequences of Hurricanes Helene and Milton, highlighting the challenges faced by impacted communities in terms of infrastructure, economic stability, and overall resilience.\n",
              "\n",
              "**Paragraph 2: Contrasting Impacts of Helene and Milton**\n",
              "\n",
              "Hurricane Helene's impact was most acutely felt in the Appalachian region of North Carolina, where record-breaking rainfall led to catastrophic flooding and landslides. The storm claimed over 100 lives in the state and caused extensive damage to infrastructure, isolating communities and disrupting essential services. In contrast, Hurricane Milton, while less deadly, spawned a series of tornadoes in Florida, causing significant structural damage and disrupting air travel. The economic consequences also varied, with Helene severely impacting tourism and agriculture in the Appalachian region, while Milton primarily affected coastal communities and infrastructure in Florida. The differing impacts underscore the importance of considering the specific vulnerabilities of each region when preparing for and responding to hurricanes.\n",
              "\n",
              "**Paragraph 3: Lessons Learned and the Future of Hurricane Preparedness**\n",
              "\n",
              "The experiences of Hurricanes Helene and Milton in 2024 offer valuable lessons for future hurricane preparedness and disaster management. The need for resilient infrastructure, effective evacuation plans, and coordinated disaster relief efforts was evident in both cases. Furthermore, the increasing intensity of these storms highlights the urgent need to address climate change and its contribution to extreme weather events. By understanding the distinct impacts of these hurricanes and investing in proactive measures, communities can better protect themselves from the devastating consequences of future storms.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "display(Markdown(s[\"generate\"][\"draft\"]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c01d26c8df5b"
      },
      "source": [
        "## Additional Resources\n",
        "\n",
        "- [Google Cloud Generative AI repository on GitHub](https://github.com/GoogleCloudPlatform/generative-ai/)\n",
        "- [Gemini API in Google AI Studio](https://ai.google.dev/gemini-api/docs)\n",
        "- [Gemini API in Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/overview)\n",
        "- [LangGraph tutorials](https://langchain-ai.github.io/langgraph/tutorials/)\n",
        "- [DeepLearning.AI course on AI Agents in LangGraph](https://www.deeplearning.ai/short-courses/ai-agents-in-langgraph/)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "ai_agents_for_engineers.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
