{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# 📋 Day 1: In-Class Assignment\n",
        "# LLM Business Application Prototype\n",
        "\n",
        "## Time: 90 minutes\n",
        "\n",
        "---\n",
        "\n",
        "## Scenario\n",
        "\n",
        "You are a consultant hired by **RetailMax**, a mid-size retail company with 50 stores.\n",
        "They want to understand how Large Language Models could help their business.\n",
        "\n",
        "Your task is to create a **working prototype** demonstrating one valuable LLM application.\n",
        "\n",
        "---\n",
        "\n",
        "## Deliverables\n",
        "\n",
        "| # | Deliverable | Points |\n",
        "|---|-------------|--------|\n",
        "| 1 | Working implementation | 30 |\n",
        "| 2 | Business value explanation | 25 |\n",
        "| 3 | Three example inputs/outputs | 25 |\n",
        "| 4 | Limitations and improvements | 20 |\n",
        "| | **Total** | **100** |\n",
        "\n",
        "---\n",
        "\n",
        "## Choose Your Application\n",
        "\n",
        "Select ONE of the following (or propose your own with instructor approval):\n",
        "\n",
        "1. **Customer Review Response Generator** - Generate professional responses to customer reviews\n",
        "2. **Product Description Writer** - Create descriptions from product specifications\n",
        "3. **Internal Memo Summarizer** - Summarize company memos for busy executives\n",
        "4. **Job Posting Generator** - Create job postings from basic requirements\n",
        "5. **Your Own Idea** - Get instructor approval first\n",
        "\n",
        "---\n",
        "\n",
        "## 🎯 Quality Checklist\n",
        "\n",
        "Before submitting, verify your outputs meet these standards:\n",
        "\n",
        "- [ ] Output follows the required format\n",
        "- [ ] No invented facts (only uses information from input)\n",
        "- [ ] Missing info is labeled or handled gracefully\n",
        "- [ ] Output is concise and within constraints\n",
        "- [ ] Spot-checked at least 2 outputs manually\n",
        "- [ ] Edge cases considered (what if input is unusual?)"
      ],
      "metadata": {
        "id": "dhYelr0TuuLY"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup"
      ],
      "metadata": {
        "id": "u2zA5Zi3uuLb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip -q install -U google-genai"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rOT06uQ2uuLb",
        "outputId": "dad4945b-1093-42d2-c531-3806ebae4b06"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.1/53.1 kB\u001b[0m \u001b[31m2.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m719.4/719.4 kB\u001b[0m \u001b[31m13.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m234.9/234.9 kB\u001b[0m \u001b[31m9.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
            "google-colab 1.0.0 requires google-auth==2.43.0, but you have google-auth 2.47.0 which is incompatible.\u001b[0m\u001b[31m\n",
            "\u001b[0m"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import json\n",
        "import time\n",
        "import re\n",
        "from datetime import datetime, timezone\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "\n",
        "# --- Load API key ---\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    os.environ[\"GEMINI_API_KEY\"] = userdata.get(\"GEMINI_API_KEY\")\n",
        "except Exception:\n",
        "    pass\n",
        "\n",
        "if not os.environ.get(\"GEMINI_API_KEY\"):\n",
        "    import getpass\n",
        "    os.environ[\"GEMINI_API_KEY\"] = getpass.getpass(\"Paste your GEMINI_API_KEY (input hidden): \")\n",
        "\n",
        "# Initialize client\n",
        "client = genai.Client()\n",
        "MODEL_ID = \"gemini-2.0-flash-lite\"\n",
        "\n",
        "# --- Prompt Logging ---\n",
        "PROMPT_LOG = []\n",
        "\n",
        "def _now():\n",
        "    return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')\n",
        "\n",
        "def generate(prompt, temperature=0.7, max_tokens=500, log=True):\n",
        "    \"\"\"Generate text using Gemini with logging.\"\"\"\n",
        "    t0 = time.time()\n",
        "    response = client.models.generate_content(\n",
        "        model=MODEL_ID,\n",
        "        contents=prompt,\n",
        "        config=types.GenerateContentConfig(\n",
        "            temperature=temperature,\n",
        "            max_output_tokens=max_tokens\n",
        "        )\n",
        "    )\n",
        "    text = response.text or \"\"\n",
        "    latency = time.time() - t0\n",
        "\n",
        "    if log:\n",
        "        PROMPT_LOG.append({\n",
        "            \"ts\": _now(),\n",
        "            \"temperature\": temperature,\n",
        "            \"prompt\": prompt,\n",
        "            \"output\": text,\n",
        "            \"latency_s\": round(latency, 3)\n",
        "        })\n",
        "    return text\n",
        "\n",
        "def try_parse_json(text):\n",
        "    \"\"\"Attempt to parse JSON from LLM output.\"\"\"\n",
        "    try:\n",
        "        return True, json.loads(text)\n",
        "    except json.JSONDecodeError:\n",
        "        pass\n",
        "    json_match = re.search(r'```(?:json)?\\s*([\\s\\S]*?)```', text)\n",
        "    if json_match:\n",
        "        try:\n",
        "            return True, json.loads(json_match.group(1))\n",
        "        except json.JSONDecodeError:\n",
        "            pass\n",
        "    json_match = re.search(r'[\\[\\{][\\s\\S]*[\\]\\}]', text)\n",
        "    if json_match:\n",
        "        try:\n",
        "            return True, json.loads(json_match.group())\n",
        "        except json.JSONDecodeError:\n",
        "            pass\n",
        "    return False, None\n",
        "\n",
        "print(\"✅ Setup complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1QSaSOJwuuLc",
        "outputId": "ceed180c-e9db-4562-8884-bd23330e7dfe"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "✅ Setup complete!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## Part 1: Business Value Explanation (25 points)\n",
        "\n",
        "### 1.1 Application Name and Description\n",
        "\n",
        "**Application Name:** RetailMax Review Response Generator\n",
        "\n",
        "**Brief Description:** An LLM-powered tool that automatically generates professional, empathetic responses to customer reviews based on star rating and review content, saving customer service teams significant time while maintaining brand voice consistency.\n",
        "\n",
        "### 1.2 Business Problem Solved\n",
        "\n",
        "**Current Pain Point:**  RetailMax's customer service team manually writes responses to hundreds of customer reviews across platforms (Google, Yelp, Amazon). This process takes 5-10 minutes per review, leads to inconsistent tone and quality, and delays responses, negatively impacting customer satisfaction scores.\n",
        "\n",
        "**Who Benefits:**\n",
        "\n",
        "a. Customer Service Representatives (primary users)\n",
        "\n",
        "b. Social Media Manager\n",
        "\n",
        "c. Brand/PR Department\n",
        "\n",
        "d. Store Managers who monitor local reviews\n",
        "\n",
        "### 1.3 Expected Value\n",
        "\n",
        "**Time Savings:** Reduces response time from 10 minutes to 30 seconds per review (95% reduction). For 50 stores averaging 20 reviews/week each, this saves approximately 83 hours weekly.\n",
        "\n",
        "**Quality Improvement:** Ensures consistent brand voice, empathetic tone matching review sentiment, and professional formatting across all responses.\n",
        "\n",
        "**Other Benefits:**\n",
        "\n",
        "Enables faster response times improving review platform algorithms\n",
        "\n",
        "Provides training examples for new customer service hires\n",
        "\n",
        "Maintains compliance with company policies in all responses\n",
        "\n",
        "Scalable during peak seasons without additional staffing"
      ],
      "metadata": {
        "id": "As_1KfeBuuLd"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## Part 2: Implementation (30 points)"
      ],
      "metadata": {
        "id": "x0VyWq2wuuLd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# YOUR MAIN FUNCTION\n",
        "#\n",
        "# Requirements:\n",
        "# - Clear function name and docstring\n",
        "# - Well-structured prompt with explicit rules\n",
        "# - Include \"do not invent facts\" instruction\n",
        "# - Appropriate temperature setting\n",
        "\n",
        "def generate_review_response(review_text, rating, product_name=None, store_location=None):\n",
        "    \"\"\"\n",
        "    Generate a professional, empathetic response to customer reviews for RetailMax.\n",
        "\n",
        "    Args:\n",
        "        review_text (str): The customer's review text\n",
        "        rating (int): Star rating (1-5)\n",
        "        product_name (str, optional): Name of product mentioned in review\n",
        "        store_location (str, optional): Store location if mentioned\n",
        "\n",
        "    Returns:\n",
        "        str: Professional response tailored to review sentiment and content\n",
        "    \"\"\"\n",
        "\n",
        "   # Define tone guidelines based on rating\n",
        "    tone_guide = {\n",
        "        5: \"enthusiastic, grateful, and celebratory\",\n",
        "        4: \"appreciative, warm, and encouraging\",\n",
        "        3: \"understanding, helpful, and solution-oriented\",\n",
        "        2: \"empathetic, apologetic, and focused on resolution\",\n",
        "        1: \"deeply apologetic, concerned, and action-oriented with specific next steps\"\n",
        "    }\n",
        "\n",
        "    # Extract context for personalization\n",
        "    context_info = \"\"\n",
        "    if product_name:\n",
        "        context_info += f\"Product mentioned: {product_name}\\n\"\n",
        "    if store_location:\n",
        "        context_info += f\"Store location: {store_location}\\n\"\n",
        "\n",
        "    tone = tone_guide.get(rating, tone_guide[3]) #change as per requirement\n",
        "\n",
        "    prompt =  f\"\"\"You are a customer service specialist for RetailMax, a mid-size retail company with 50 stores.\n",
        "Generate a professional response to this customer review that matches the sentiment and addresses specific points mentioned.\n",
        "\n",
        "Review Details:\n",
        "Rating: {rating}/5 stars\n",
        "{context_info}Review: {review_text}\n",
        "\n",
        "Response Requirements:\n",
        "1. TONE: Be {tone} - match the customer's sentiment appropriately\n",
        "2. PERSONALIZATION: Reference specific points from their review (do not be generic)\n",
        "3. ACTION: If rating is 3 or below, offer a specific solution or next step\n",
        "4. BRAND VOICE: Professional but approachable, representing RetailMax values\n",
        "5. LENGTH: 80-120 words\n",
        "6. SIGNATURE: End with \"The RetailMax Team\" and appropriate contact info if needed\n",
        "\n",
        "Critical Rules:\n",
        "- DO NOT invent facts not present in the review\n",
        "- DO NOT make promises about discounts/refunds unless implied by standard policy\n",
        "- DO NOT share internal contact information\n",
        "- If product/store not specified, use generic but appropriate references\n",
        "- For 1-2 star reviews, acknowledge the seriousness and provide escalation path\n",
        "\n",
        "Response:\"\"\"\n",
        "\n",
        "    # Temperature settings based on Independent Lab experiments\n",
        "    # Lower temperature for consistency in customer service responses\n",
        "    temperature = 0.3 if rating <= 3 else 0.4\n",
        "\n",
        "    return generate(prompt, temperature=temperature, max_tokens=300)"
      ],
      "metadata": {
        "id": "JVY0zP76uuLd"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## Part 3: Example Inputs/Outputs (25 points)\n",
        "\n",
        "### Example 1: Typical Use Case  (5-Star positive review)"
      ],
      "metadata": {
        "id": "nIt44UoguuLe"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "example1_input = {\n",
        "    \"review_text\": \"Absolutely love these headphones! The noise cancellation is incredible - I can't hear my coworkers at all. Battery life lasts all day and the comfort is perfect for long work sessions.\",\n",
        "    \"rating\": 5,\n",
        "    \"product_name\": \"SoundWave Pro Headphones\",\n",
        "    \"store_location\": \"Boston Downtown\"\n",
        "}\n",
        "\n",
        "print(\"=\"*60)\n",
        "print(\"EXAMPLE 1: Typical Use Case - 5-Star Positive Review\")\n",
        "print(\"=\"*60)\n",
        "print(\"\\n📥 INPUT:\")\n",
        "print(f\"Rating: {example1_input['rating']}/5\")\n",
        "print(f\"Product: {example1_input['product_name']}\")\n",
        "print(f\"Store: {example1_input['store_location']}\")\n",
        "print(f\"Review: {example1_input['review_text']}\")\n",
        "print(\"\\n📤 OUTPUT:\")\n",
        "response = generate_review_response(\n",
        "    review_text=example1_input['review_text'],\n",
        "    rating=example1_input['rating'],\n",
        "    product_name=example1_input['product_name'],\n",
        "    store_location=example1_input['store_location']\n",
        ")\n",
        "print(response)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QbkbVav3uuLe",
        "outputId": "757d2f53-342c-4460-93a2-85497dff896b"
      },
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "EXAMPLE 1: Typical Use Case - 5-Star Positive Review\n",
            "============================================================\n",
            "\n",
            "📥 INPUT:\n",
            "Rating: 5/5\n",
            "Product: SoundWave Pro Headphones\n",
            "Store: Boston Downtown\n",
            "Review: Absolutely love these headphones! The noise cancellation is incredible - I can't hear my coworkers at all. Battery life lasts all day and the comfort is perfect for long work sessions.\n",
            "\n",
            "📤 OUTPUT:\n",
            "Wow, thank you so much for the fantastic 5-star review! We're absolutely thrilled to hear you're loving your new SoundWave Pro Headphones! It's music to our ears that the noise cancellation is doing the trick and blocking out your coworkers – we know how important that can be for focus! We're also delighted the battery life and comfort are meeting your needs for those long work sessions.\n",
            "\n",
            "We're so glad you had a positive experience at our Boston Downtown store. We appreciate you choosing RetailMax! Enjoy your headphones!\n",
            "\n",
            "The RetailMax Team\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Example 1 Quality Assessment:**\n",
        "- Does output follow format? Yes - Proper greeting, personalized content, appropriate length, signature\n",
        "- Any invented facts? No - Only references battery life, noise cancellation, and comfort mentioned in review\n",
        "- Overall quality: Good - Enthusiastic tone matches 5-star rating, specific to review content\n",
        "- Notes: Successfully personalized by mentioning specific features praised by customer\n",
        "\n"
      ],
      "metadata": {
        "id": "V2E32q1NuuLe"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Example 2: Different Scenario (3-star mixed review)"
      ],
      "metadata": {
        "id": "tBoL3jPlzCF_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "example2_input = {\n",
        "    \"review_text\": \"The jacket looks great and is warm, but the zipper broke after 2 weeks. Customer service was helpful but said it would take 3 weeks to get a replacement. For the price, I expected better quality.\",\n",
        "    \"rating\": 3,\n",
        "    \"product_name\": \"Alpine Winter Jacket\",\n",
        "    \"store_location\": None  # Not specified in review\n",
        "}\n",
        "\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 2: Different Scenario - 3-Star Mixed Review\")\n",
        "print(\"=\"*60)\n",
        "print(\"\\n📥 INPUT:\")\n",
        "print(f\"Rating: {example2_input['rating']}/5\")\n",
        "print(f\"Product: {example2_input['product_name']}\")\n",
        "print(f\"Review: {example2_input['review_text']}\")\n",
        "print(\"\\n📤 OUTPUT:\")\n",
        "response = generate_review_response(\n",
        "    review_text=example2_input['review_text'],\n",
        "    rating=example2_input['rating'],\n",
        "    product_name=example2_input['product_name']\n",
        ")\n",
        "print(response)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fwgK_IcjuuLf",
        "outputId": "0187f734-0d16-43ed-bd38-b08582c0ab7d"
      },
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "============================================================\n",
            "EXAMPLE 2: Different Scenario - 3-Star Mixed Review\n",
            "============================================================\n",
            "\n",
            "📥 INPUT:\n",
            "Rating: 3/5\n",
            "Product: Alpine Winter Jacket\n",
            "Review: The jacket looks great and is warm, but the zipper broke after 2 weeks. Customer service was helpful but said it would take 3 weeks to get a replacement. For the price, I expected better quality.\n",
            "\n",
            "📤 OUTPUT:\n",
            "Dear [Customer Name],\n",
            "\n",
            "Thank you for taking the time to share your feedback on the Alpine Winter Jacket. We're truly sorry to hear that the zipper broke after only two weeks, and we understand your frustration, especially given the price point. We also appreciate you acknowledging that our customer service team was helpful, even though the replacement timeframe of three weeks wasn't ideal.\n",
            "\n",
            "We strive for quality and are disappointed to learn the jacket didn't meet your expectations. To help resolve this, please reply to this message with your order number, and we'll expedite the replacement process. We want to ensure you get a fully functional jacket as quickly as possible.\n",
            "\n",
            "The RetailMax Team\n",
            "[RetailMax Customer Service Email Address or Phone Number]\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Example 2 Quality Assessment:**\n",
        "- Does output follow format? Yes - Acknowledges both positive and negative aspects\n",
        "- Any invented facts? No - Only addresses jacket appearance, warmth, zipper issue, and replacement timeline mentioned\n",
        "- Overall quality: Good - Balanced tone, offers solution without overpromising\n",
        "- Notes: Correctly handles missing store location, focuses on resolution for the zipper issue\n",
        "\n"
      ],
      "metadata": {
        "id": "TC_86SULuuLf"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Example 3: Edge Case (1-star angry review with vague complaint)"
      ],
      "metadata": {
        "id": "bKMgimZjzeHe"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "example3_input = {\n",
        "    \"review_text\": \"WORST EXPERIENCE EVER!!! Never shopping here again. Complete waste of time and money.\",\n",
        "    \"rating\": 1,\n",
        "    \"product_name\": None,  # No product specified\n",
        "    \"store_location\": None  # No location specified\n",
        "}\n",
        "\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 3: Edge Case - 1-Star Vague Angry Review\")\n",
        "print(\"=\"*60)\n",
        "print(\"\\n📥 INPUT:\")\n",
        "print(f\"Rating: {example1_input['rating']}/5\")\n",
        "print(f\"Review: {example3_input['review_text']}\")\n",
        "print(\"\\n📤 OUTPUT:\")\n",
        "response = generate_review_response(\n",
        "    review_text=example3_input['review_text'],\n",
        "    rating=example3_input['rating']\n",
        ")\n",
        "print(response)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fxCwgFEYuuLf",
        "outputId": "dd8eb2f2-a147-47e0-efd8-3afc16b66022"
      },
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "============================================================\n",
            "EXAMPLE 3: Edge Case - 1-Star Vague Angry Review\n",
            "============================================================\n",
            "\n",
            "📥 INPUT:\n",
            "Rating: 5/5\n",
            "Review: WORST EXPERIENCE EVER!!! Never shopping here again. Complete waste of time and money.\n",
            "\n",
            "📤 OUTPUT:\n",
            "Dear Valued Customer,\n",
            "\n",
            "I am so incredibly sorry to hear about the truly awful experience you had at RetailMax. I understand your frustration and disappointment, and I sincerely apologize that your visit was a complete waste of your time and money. We strive to provide a positive shopping experience, and it's clear we failed you.\n",
            "\n",
            "This is not the standard we hold ourselves to, and I want to make things right. Please contact us directly at [Phone Number] or reply to this message so we can gather more details about your visit and determine how to best address the issues you encountered. We value your feedback and want to regain your trust.\n",
            "\n",
            "The RetailMax Team\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Example 3 Quality Assessment:**\n",
        "- Does output follow format? Yes - Maintains professional structure despite vague input\n",
        "- Any invented facts? No - Doesn't speculate about specific issues\n",
        "- How did it handle the edge case? Well - Acknowledges frustration without specifics, provides escalation path, maintains professionalism\n",
        "- Notes:  Successfully handles complete lack of specifics by offering direct contact option while expressing empathy"
      ],
      "metadata": {
        "id": "gpro-YWkuuLf"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## Part 4: Limitations and Improvements (20 points)\n",
        "\n",
        "### 4.1 Current Limitations\n",
        "\n",
        "List at least 3 limitations of your current implementation:\n",
        "\n",
        "1. **Limitation 1:** Cannot verify review authenticity or customer purchase history - may respond to fake or inaccurate reviews.\n",
        "\n",
        "2. **Limitation 2:** Limited context window - cannot reference previous interactions with the same customer or complex purchase histories.\n",
        "\n",
        "3. **Limitation 3:** No sentiment analysis beyond star rating - may miss sarcasm or nuanced emotions in review text.\n",
        "\n",
        "4. **Limitation 4:** Cannot handle multilingual reviews - assumes English input only.\n",
        "\n",
        "5. **Limitation 5:** No integration with CRM systems - responses are generated in isolation without customer history.\n",
        "\n",
        "### 4.2 Potential Improvements\n",
        "\n",
        "How would you improve this for production use?\n",
        "\n",
        "1. **Technical:** Can add input validation and pre-processing to detect and flag potentially fake reviews, sarcasm, or non-English text before generation.\n",
        "\n",
        "2. **Business:** Integrate with RetailMax's CRM to pull customer purchase history, enabling personalized references to past purchases and loyalty status.\n",
        "\n",
        "3. **Quality:** (HITL)Implement a review workflow where AI-generated responses are queued for human approval for 1-2 star reviews before sending, ensuring sensitive cases get expert attention.\n",
        "\n",
        "4. **Scalability:** Create a feedback loop where customer service agents can rate AI responses, continuously improving the model with reinforcement learning.\n",
        "\n",
        "5. **Multilingual Support:** Add language detection and translation capabilities to handle reviews in Spanish, Chinese, and other common languages among RetailMax's customer base.\n",
        "\n",
        "### 4.3 When NOT to Use This Tool\n",
        "\n",
        "Describe scenarios where this tool should NOT be used without human review:\n",
        "\n",
        "1. **Legal or safety concerns:** Reviews mentioning injuries, product safety issues, or potential legal action should immediately escalate to legal/compliance teams.\n",
        "\n",
        "2. **High-value customers:** Loyalty program members with high lifetime value deserve personalized human responses, not automated ones.\n",
        "\n",
        "3. **Complex complaint chains:** When review references multiple previous unresolved issues, a human should review the full history.\n",
        "\n",
        "4. **Brand reputation crises:** During viral negative incidents, all responses should be coordinated by PR/communications team.\n",
        "\n",
        "5. **Requests for specific policy exceptions:** When customers ask for exceptions to return/refund policies that require managerial approval."
      ],
      "metadata": {
        "id": "iZ26nPlCuuLg"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## Export Your Work"
      ],
      "metadata": {
        "id": "PMt2aJm-uuLg"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pandas as pd\n",
        "from datetime import datetime\n",
        "\n",
        "# Save prompt log with additional metadata\n",
        "df = pd.DataFrame(PROMPT_LOG)\n",
        "\n",
        "# Add assignment metadata\n",
        "df['assignment'] = 'Day1_Assignment1'\n",
        "df['application'] = 'Review Response Generator'\n",
        "df['export_time'] = datetime.now().isoformat()\n",
        "\n",
        "df.to_csv(\"day1_assignment_prompt_log.csv\", index=False)\n",
        "print(f\"✅ Saved {len(df)} prompts to: day1_assignment_prompt_log.csv\")\n",
        "print(f\"📊 Prompt log includes {len(df)} API calls with average latency of {df['latency_s'].mean():.2f}s\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "kSu1LwSGuuLg",
        "outputId": "a5fe1114-03e4-4e34-dc5b-1d1eb02422c8"
      },
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "✅ Saved 3 prompts to: day1_assignment_prompt_log.csv\n",
            "📊 Prompt log includes 3 API calls with average latency of 1.47s\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "## ✅ Submission Checklist\n",
        "\n",
        "Before submitting, ensure you have:\n",
        "\n",
        "- [ ] Completed business value explanation (Part 1)\n",
        "- [ ] Working implementation with clear prompt (Part 2)\n",
        "- [ ] Three diverse examples with quality assessments (Part 3)\n",
        "- [ ] Thoughtful limitations analysis (Part 4)\n",
        "- [ ] All cells executed with outputs\n",
        "- [ ] Prompt log exported\n",
        "\n",
        "---\n",
        "\n",
        "## 📊 Grading Rubric\n",
        "\n",
        "| Criterion | Excellent (90-100%) | Good (70-89%) | Needs Work (<70%) |\n",
        "|-----------|---------------------|---------------|-------------------|\n",
        "| **Implementation (30)** | Code runs perfectly, well-structured prompt with rules | Code runs with minor issues | Code has errors |\n",
        "| **Business Value (25)** | Clear, specific value with quantified benefits | Value present but vague | Weak justification |\n",
        "| **Examples (25)** | 3 diverse examples with quality assessments | 3 examples but limited analysis | Fewer than 3 |\n",
        "| **Limitations (20)** | Thoughtful, specific with actionable improvements | Generic limitations | Missing |\n",
        "\n",
        "**Score:** ___ / 100"
      ],
      "metadata": {
        "id": "Nz-TCVb1uuLg"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "---\n",
        "\n",
        "# 📎 APPENDIX: Sample Solutions\n",
        "\n",
        "Use for reference AFTER attempting your own solution."
      ],
      "metadata": {
        "id": "bbt-DK1duuLh"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Sample A: Customer Review Response Generator"
      ],
      "metadata": {
        "id": "AzJq_N_2uuLh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def generate_review_response(review_text, rating, product_name, store_name=\"RetailMax\"):\n",
        "    \"\"\"\n",
        "    Generate a professional response to a customer review.\n",
        "\n",
        "    Args:\n",
        "        review_text (str): The customer's review\n",
        "        rating (int): Star rating (1-5)\n",
        "        product_name (str): Name of the product reviewed\n",
        "        store_name (str): Name of the store\n",
        "\n",
        "    Returns:\n",
        "        str: Professional response to the review\n",
        "    \"\"\"\n",
        "    tone_guide = {\n",
        "        5: \"enthusiastic and grateful\",\n",
        "        4: \"appreciative and warm\",\n",
        "        3: \"understanding and helpful\",\n",
        "        2: \"empathetic and solution-focused\",\n",
        "        1: \"deeply apologetic and action-oriented\"\n",
        "    }\n",
        "\n",
        "    tone = tone_guide.get(rating, tone_guide[3])\n",
        "\n",
        "    prompt = f\"\"\"You are a customer service representative for {store_name}.\n",
        "Write a response to this customer review.\n",
        "\n",
        "Product: {product_name}\n",
        "Rating: {rating}/5 stars\n",
        "Review: {review_text}\n",
        "\n",
        "Be {tone}.\n",
        "\n",
        "Rules:\n",
        "- Thank them for feedback\n",
        "- Reference specific points from their review (do not be generic)\n",
        "- If rating <= 3, offer a specific solution or next step\n",
        "- Keep under 100 words\n",
        "- Do not invent facts not in the review\n",
        "- Sign off as \"The {store_name} Team\"\n",
        "\n",
        "Response:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.4)\n",
        "\n",
        "\n",
        "# Test\n",
        "print(\"=== 5-STAR ===\")\n",
        "print(generate_review_response(\n",
        "    \"Amazing headphones! Battery lasts forever!\",\n",
        "    5, \"SoundWave Pro\"\n",
        "))\n",
        "\n",
        "print(\"\\n=== 2-STAR ===\")\n",
        "print(generate_review_response(\n",
        "    \"Stopped working after 2 weeks. Very disappointed.\",\n",
        "    2, \"SoundWave Pro\"\n",
        "))"
      ],
      "metadata": {
        "id": "3OvWDBttuuLh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Sample B: Product Description Writer"
      ],
      "metadata": {
        "id": "5UK9dkOvuuLh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def generate_product_description(product_name, specifications, target_audience):\n",
        "    \"\"\"\n",
        "    Generate a product description from specifications.\n",
        "\n",
        "    Args:\n",
        "        product_name (str): Name of the product\n",
        "        specifications (dict): Product specs\n",
        "        target_audience (str): Who it's for\n",
        "\n",
        "    Returns:\n",
        "        str: Compelling product description\n",
        "    \"\"\"\n",
        "    specs_text = \"\\n\".join([f\"- {k}: {v}\" for k, v in specifications.items()])\n",
        "\n",
        "    prompt = f\"\"\"Write a product description for an e-commerce website.\n",
        "\n",
        "Product: {product_name}\n",
        "\n",
        "Specifications:\n",
        "{specs_text}\n",
        "\n",
        "Target Audience: {target_audience}\n",
        "\n",
        "Rules:\n",
        "- Engaging opening (no generic \"Introducing...\")\n",
        "- Translate specs into customer benefits\n",
        "- Include 2-3 use cases\n",
        "- Only mention features from the specifications above\n",
        "- Do not invent features not listed\n",
        "- 100-150 words\n",
        "\n",
        "Description:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.6)\n",
        "\n",
        "\n",
        "# Test\n",
        "specs = {\n",
        "    \"Weight\": \"250g\",\n",
        "    \"Battery\": \"40 hours\",\n",
        "    \"Connectivity\": \"Bluetooth 5.0\",\n",
        "    \"ANC\": \"Hybrid with transparency mode\"\n",
        "}\n",
        "\n",
        "print(generate_product_description(\n",
        "    \"SoundWave Pro Headphones\",\n",
        "    specs,\n",
        "    \"Remote professionals\"\n",
        "))"
      ],
      "metadata": {
        "id": "BnC8TAqTuuLi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Sample C: Internal Memo Summarizer"
      ],
      "metadata": {
        "id": "dJ8W5by1uuLi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def summarize_memo(memo_text, summary_format=\"executive\"):\n",
        "    \"\"\"\n",
        "    Summarize an internal company memo.\n",
        "\n",
        "    Args:\n",
        "        memo_text (str): Full memo\n",
        "        summary_format (str): \"executive\", \"action\", or \"team\"\n",
        "\n",
        "    Returns:\n",
        "        str: Formatted summary\n",
        "    \"\"\"\n",
        "    formats = {\n",
        "        \"executive\": \"3-sentence summary: key decision, impact, timeline.\",\n",
        "        \"action\": \"Numbered list of action items with owners and deadlines.\",\n",
        "        \"team\": \"TL;DR (1 sentence), Key Points (bullets), Action Items.\"\n",
        "    }\n",
        "\n",
        "    prompt = f\"\"\"Summarize this internal memo.\n",
        "\n",
        "Memo:\n",
        "{memo_text}\n",
        "\n",
        "Format: {formats.get(summary_format, formats['executive'])}\n",
        "\n",
        "Rules:\n",
        "- Only include information from the memo\n",
        "- If owner/deadline not mentioned, write \"Not specified\"\n",
        "- Do not invent facts\n",
        "\n",
        "Summary:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.2)\n",
        "\n",
        "\n",
        "# Test\n",
        "memo = \"\"\"\n",
        "TO: All Department Heads\n",
        "FROM: CEO\n",
        "RE: Q1 2025 Initiatives\n",
        "\n",
        "We're increasing digital investment by 25% ($2M to IT).\n",
        "Sarah Chen leads this with Deloitte support.\n",
        "\n",
        "New CRM training for all stores by March 15.\n",
        "Regional managers: submit schedules to HR by Jan 25.\n",
        "\n",
        "Travel freeze until Q2. Requests over $500 need VP approval.\n",
        "\n",
        "3% cost-of-living raise effective Feb 1.\n",
        "\n",
        "Q&A session: Jan 22 at 2pm.\n",
        "\"\"\"\n",
        "\n",
        "print(\"=== EXECUTIVE ===\")\n",
        "print(summarize_memo(memo, \"executive\"))\n",
        "\n",
        "print(\"\\n=== ACTIONS ===\")\n",
        "print(summarize_memo(memo, \"action\"))"
      ],
      "metadata": {
        "id": "sWQbDmO_uuLi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Sample D: Job Posting Generator"
      ],
      "metadata": {
        "id": "rJTdwUWMuuLj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def generate_job_posting(job_title, department, requirements, nice_to_have=None):\n",
        "    \"\"\"\n",
        "    Generate a job posting from requirements.\n",
        "\n",
        "    Args:\n",
        "        job_title (str): Position title\n",
        "        department (str): Department\n",
        "        requirements (list): Required qualifications\n",
        "        nice_to_have (list): Optional qualifications\n",
        "\n",
        "    Returns:\n",
        "        str: Complete job posting\n",
        "    \"\"\"\n",
        "    reqs = \"\\n\".join([f\"- {r}\" for r in requirements])\n",
        "    nice = \"\\n\".join([f\"- {n}\" for n in (nice_to_have or [])])\n",
        "\n",
        "    prompt = f\"\"\"Write a job posting for RetailMax, a mid-size retail company.\n",
        "\n",
        "Position: {job_title}\n",
        "Department: {department}\n",
        "\n",
        "Required Qualifications:\n",
        "{reqs}\n",
        "\n",
        "{\"Nice to Have:\" if nice_to_have else \"\"}\n",
        "{nice if nice_to_have else \"\"}\n",
        "\n",
        "Include these sections:\n",
        "1. Engaging opening paragraph about the role\n",
        "2. \"What You'll Do\" (5 responsibilities based on the role)\n",
        "3. \"What You'll Bring\" (from requirements above)\n",
        "4. \"Why Join Us\" (standard retail company benefits)\n",
        "\n",
        "Rules:\n",
        "- Only use requirements listed above\n",
        "- Do not add qualifications not provided\n",
        "- 300-400 words\n",
        "- Professional but approachable tone\n",
        "\n",
        "Job Posting:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.5)\n",
        "\n",
        "\n",
        "# Test\n",
        "reqs = [\n",
        "    \"3+ years retail management\",\n",
        "    \"Strong leadership skills\",\n",
        "    \"Inventory management experience\",\n",
        "    \"Flexible schedule including weekends\"\n",
        "]\n",
        "\n",
        "nice = [\n",
        "    \"Bachelor's in Business\",\n",
        "    \"CRM experience\",\n",
        "    \"Bilingual English/Spanish\"\n",
        "]\n",
        "\n",
        "print(generate_job_posting(\"Store Manager\", \"Retail Operations\", reqs, nice))"
      ],
      "metadata": {
        "id": "dia4V2ZuuuLj"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}