{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 🔬 Day 1: Independent Lab - Exploring LLM Applications in Business\n",
        "\n",
        "Work through these exercises independently or with a partner.\n",
        "\n",
        "## Learning Objectives\n",
        "- ✅ Apply LLMs to realistic business scenarios\n",
        "- ✅ Experiment with different prompting approaches\n",
        "- ✅ Understand the strengths and limitations of LLMs\n",
        "- ✅ Build intuition for parameter tuning\n",
        "\n",
        "## Time: 90 minutes\n",
        "\n",
        "## Structure\n",
        "- **Task 1**: Content Generation Suite (25 min)\n",
        "- **Task 2**: Text Transformation (25 min)\n",
        "- **Task 3**: Interactive Q&A System (25 min)\n",
        "- **Stretch Task**: Creative Application (15 min)\n",
        "\n",
        "---\n",
        "\n",
        "## 🎯 Ground Rules (Remember These!)\n",
        "\n",
        "1. **If unsure, say so** - LLMs should acknowledge uncertainty\n",
        "2. **Output format matters** - Specify the format you need\n",
        "3. **Don't invent facts** - Only use information from the input\n",
        "4. **Verify important outputs** - Spot-check critical results\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup\n",
        "\n",
        "Run these cells first to set up your environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!pip -q install -U google-genai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "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",
        "    \"\"\"\n",
        "    Generate text using Gemini with logging.\n",
        "    \"\"\"\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",
        "            \"model\": MODEL_ID,\n",
        "            \"temperature\": temperature,\n",
        "            \"max_tokens\": max_tokens,\n",
        "            \"prompt\": prompt,\n",
        "            \"output\": text,\n",
        "            \"latency_s\": round(latency, 3)\n",
        "        })\n",
        "    return text\n",
        "\n",
        "def try_parse_json(text):\n",
        "    \"\"\"\n",
        "    Attempt to parse JSON from LLM output.\n",
        "    Returns (success: bool, parsed_data or None)\n",
        "    \"\"\"\n",
        "    # Direct parse\n",
        "    try:\n",
        "        return True, json.loads(text)\n",
        "    except json.JSONDecodeError:\n",
        "        pass\n",
        "\n",
        "    # Extract from code blocks\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",
        "\n",
        "    # Find JSON in text\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",
        "\n",
        "    return False, None\n",
        "\n",
        "def show_log(n=3):\n",
        "    \"\"\"Display the last n entries from the prompt log.\"\"\"\n",
        "    for row in PROMPT_LOG[-n:]:\n",
        "        print(\"=\" * 70)\n",
        "        print(f\"Time: {row['ts']} | Temp: {row['temperature']} | Latency: {row['latency_s']}s\")\n",
        "        print(\"--- PROMPT (first 400 chars) ---\")\n",
        "        print(row[\"prompt\"][:400])\n",
        "        print(\"--- OUTPUT (first 400 chars) ---\")\n",
        "        print(row[\"output\"][:400])\n",
        "\n",
        "# Test\n",
        "print(\"✅ Setup complete!\")\n",
        "print(generate(\"Say 'Ready to work!' in an enthusiastic way.\", temperature=0.8))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "---\n",
        "\n",
        "## Task 1: Content Generation Suite (25 minutes)\n",
        "\n",
        "Build a marketing copy generator that can create different types of content for a product.\n",
        "\n",
        "### 1.1 Complete the Function\n",
        "\n",
        "Fill in the TODO sections to create a flexible marketing copy generator."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def generate_marketing_copy(\n",
        "    product_name,\n",
        "    product_features,\n",
        "    target_audience,\n",
        "    style=\"professional\",\n",
        "    length=\"medium\"\n",
        "):\n",
        "    \"\"\"\n",
        "    Generate marketing copy for a product.\n",
        "\n",
        "    Args:\n",
        "        product_name (str): Name of the product\n",
        "        product_features (list): List of key features\n",
        "        target_audience (str): Description of target audience\n",
        "        style (str): Writing style (professional, casual, luxury, playful)\n",
        "        length (str): Output length (short, medium, long)\n",
        "\n",
        "    Returns:\n",
        "        str: Generated marketing copy\n",
        "    \"\"\"\n",
        "\n",
        "    # Convert length to approximate word count\n",
        "    length_guide = {\n",
        "        \"short\": \"2-3 sentences (about 50 words)\",\n",
        "        \"medium\": \"1 paragraph (about 100 words)\",\n",
        "        \"long\": \"2-3 paragraphs (about 200 words)\"\n",
        "    }\n",
        "\n",
        "    # Format features as a bullet list\n",
        "    features_text = \"\\n\".join([f\"- {feature}\" for feature in product_features])\n",
        "\n",
        "    prompt = f\"\"\"Write marketing copy for the following product.\n",
        "\n",
        "Product: {product_name}\n",
        "\n",
        "Key Features:\n",
        "{features_text}\n",
        "\n",
        "Target Audience: {target_audience}\n",
        "\n",
        "Writing Style: {style}\n",
        "\n",
        "Length: {length_guide.get(length, length_guide['medium'])}\n",
        "\n",
        "Requirements:\n",
        "- Highlight benefits for the target audience\n",
        "- Do not invent features not listed above\n",
        "- Do not include a headline - just the body copy\n",
        "\n",
        "Marketing Copy:\"\"\"\n",
        "\n",
        "    # Higher temperature for creative content\n",
        "    temperature = 0.7\n",
        "\n",
        "    return generate(prompt, temperature=temperature)\n",
        "\n",
        "\n",
        "# Test the function\n",
        "features = [\n",
        "    \"40-hour battery life\",\n",
        "    \"Active noise cancellation\",\n",
        "    \"Premium leather ear cushions\",\n",
        "    \"Bluetooth 5.0 connectivity\"\n",
        "]\n",
        "\n",
        "copy = generate_marketing_copy(\n",
        "    product_name=\"SoundWave Pro Headphones\",\n",
        "    product_features=features,\n",
        "    target_audience=\"Remote workers and digital professionals aged 25-45\",\n",
        "    style=\"professional\",\n",
        "    length=\"medium\"\n",
        ")\n",
        "\n",
        "print(\"Generated Marketing Copy:\")\n",
        "print(copy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 1.2 Generate Variations\n",
        "\n",
        "Use your function to generate different versions of the copy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generate a casual version\n",
        "casual_copy = generate_marketing_copy(\n",
        "    product_name=\"SoundWave Pro Headphones\",\n",
        "    product_features=features,\n",
        "    target_audience=\"Young professionals who work from coffee shops\",\n",
        "    style=\"casual and conversational\",\n",
        "    length=\"short\"\n",
        ")\n",
        "\n",
        "print(\"=== CASUAL VERSION ===\")\n",
        "print(casual_copy)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generate a luxury/premium version\n",
        "luxury_copy = generate_marketing_copy(\n",
        "    product_name=\"SoundWave Pro Headphones\",\n",
        "    product_features=features,\n",
        "    target_audience=\"Executives and audiophiles who appreciate quality\",\n",
        "    style=\"luxury and sophisticated\",\n",
        "    length=\"medium\"\n",
        ")\n",
        "\n",
        "print(\"=== LUXURY VERSION ===\")\n",
        "print(luxury_copy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 1.3 Temperature Experiment\n",
        "\n",
        "Generate the same copy with different temperatures and compare."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "tagline_prompt = \"\"\"Write a short, catchy tagline for SoundWave Pro Headphones,\n",
        "premium wireless headphones for professionals. One sentence only.\"\"\"\n",
        "\n",
        "print(\"=== LOW TEMPERATURE (0.2) ===\")\n",
        "for i in range(3):\n",
        "    result = generate(tagline_prompt, temperature=0.2)\n",
        "    print(f\"  {i+1}: {result.strip()}\")\n",
        "\n",
        "print(\"\\n=== HIGH TEMPERATURE (1.2) ===\")\n",
        "for i in range(3):\n",
        "    result = generate(tagline_prompt, temperature=1.2)\n",
        "    print(f\"  {i+1}: {result.strip()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### ✍️ Your Notes: Task 1\n",
        "\n",
        "What did you learn about generating marketing copy?\n",
        "\n",
        "- Best temperature setting: _______\n",
        "- Most effective style for this product: _______\n",
        "- Limitations you noticed: _______\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Task 2: Text Transformation (25 minutes)\n",
        "\n",
        "Build tools that transform text in useful ways for business.\n",
        "\n",
        "### 2.1 Article Summarizer"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Sample business article\n",
        "business_article = \"\"\"\n",
        "The Rise of Remote Work: Transforming the Modern Workplace\n",
        "\n",
        "The global shift toward remote work has fundamentally altered how companies approach\n",
        "talent acquisition and retention. According to recent surveys, 78% of employees prefer\n",
        "some form of flexible working arrangement, with 45% stating they would consider leaving\n",
        "their current position if required to return to full-time office work.\n",
        "\n",
        "This paradigm shift has created both opportunities and challenges for organizations.\n",
        "On the opportunity side, companies now have access to a global talent pool, enabling\n",
        "them to recruit specialists regardless of geographic location. A tech startup in\n",
        "San Francisco can now hire a machine learning engineer from Bangalore or a UX designer\n",
        "from Berlin without requiring relocation.\n",
        "\n",
        "However, this new landscape also presents significant challenges. Maintaining company\n",
        "culture, ensuring effective collaboration, and managing across time zones require\n",
        "intentional effort and new tools. Organizations that fail to adapt their management\n",
        "practices risk decreased productivity and higher turnover.\n",
        "\n",
        "The technology sector has been at the forefront of this transformation. Companies like\n",
        "GitLab and Zapier have operated as fully remote organizations for years, developing\n",
        "best practices that are now being adopted more broadly. Their success demonstrates\n",
        "that remote work can be not just viable but advantageous.\n",
        "\n",
        "Industry analysts project that by 2025, approximately 70% of the workforce will work\n",
        "remotely at least five days per month. This trend is driving substantial investment\n",
        "in collaboration technologies, with the enterprise collaboration software market\n",
        "expected to reach $85 billion by 2026.\n",
        "\n",
        "For business leaders, the message is clear: remote work is not a temporary adjustment\n",
        "but a permanent feature of the modern workplace. Success will require new approaches\n",
        "to leadership, communication, and organizational design.\n",
        "\"\"\"\n",
        "\n",
        "print(f\"Article length: {len(business_article.split())} words\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def summarize_article(article, summary_type=\"brief\"):\n",
        "    \"\"\"\n",
        "    Summarize an article in different formats.\n",
        "\n",
        "    Args:\n",
        "        article (str): The article text\n",
        "        summary_type (str): Type of summary\n",
        "            - \"brief\": 2-3 sentences\n",
        "            - \"bullet\": Key points as bullet list\n",
        "            - \"executive\": Executive summary with recommendations\n",
        "\n",
        "    Returns:\n",
        "        str: The summary\n",
        "    \"\"\"\n",
        "\n",
        "    prompts = {\n",
        "        \"brief\": f\"\"\"Summarize this article in 2-3 sentences.\n",
        "Only include facts from the article. Do not add opinions.\n",
        "\n",
        "{article}\n",
        "\n",
        "Brief Summary:\"\"\",\n",
        "\n",
        "        \"bullet\": f\"\"\"Extract the 5 most important points from this article as bullet points.\n",
        "Each bullet should be one sentence.\n",
        "Only include facts from the article.\n",
        "\n",
        "{article}\n",
        "\n",
        "Key Points:\"\"\",\n",
        "\n",
        "        \"executive\": f\"\"\"Create an executive summary of this article for a CEO.\n",
        "Include:\n",
        "1. Main findings (2-3 sentences)\n",
        "2. Key statistics mentioned (bullet points)\n",
        "3. Recommended actions for the company (based only on article content)\n",
        "\n",
        "Article:\n",
        "{article}\n",
        "\n",
        "Executive Summary:\"\"\"\n",
        "    }\n",
        "\n",
        "    prompt = prompts.get(summary_type, prompts[\"brief\"])\n",
        "    return generate(prompt, temperature=0.3)  # Low temperature for accuracy\n",
        "\n",
        "\n",
        "# Generate different summary types\n",
        "print(\"=== BRIEF SUMMARY ===\")\n",
        "print(summarize_article(business_article, \"brief\"))\n",
        "\n",
        "print(\"\\n=== BULLET POINTS ===\")\n",
        "print(summarize_article(business_article, \"bullet\"))\n",
        "\n",
        "print(\"\\n=== EXECUTIVE SUMMARY ===\")\n",
        "print(summarize_article(business_article, \"executive\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.2 Tone Transformer\n",
        "\n",
        "Transform text from one tone/style to another."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def transform_tone(text, target_tone):\n",
        "    \"\"\"\n",
        "    Transform text to a different tone while preserving the meaning.\n",
        "\n",
        "    Args:\n",
        "        text (str): Original text\n",
        "        target_tone (str): Desired tone (simple, technical, formal, casual)\n",
        "\n",
        "    Returns:\n",
        "        str: Transformed text\n",
        "    \"\"\"\n",
        "    prompt = f\"\"\"Rewrite the following text in a {target_tone} tone.\n",
        "Keep the same meaning but change the style and vocabulary.\n",
        "Do not add new information not in the original.\n",
        "\n",
        "Original text:\n",
        "{text}\n",
        "\n",
        "Rewritten in {target_tone} tone:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.5)\n",
        "\n",
        "\n",
        "# Technical text to transform\n",
        "technical_text = \"\"\"\n",
        "The implementation leverages a microservices architecture with containerized\n",
        "deployments orchestrated via Kubernetes. Data persistence is achieved through\n",
        "a distributed PostgreSQL cluster with automatic failover capabilities.\n",
        "The API layer implements RESTful endpoints with OAuth 2.0 authentication.\n",
        "\"\"\"\n",
        "\n",
        "print(\"=== ORIGINAL (Technical) ===\")\n",
        "print(technical_text)\n",
        "\n",
        "print(\"\\n=== SIMPLIFIED (For non-technical stakeholders) ===\")\n",
        "print(transform_tone(technical_text, \"simple, easy to understand for a non-technical business person\"))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Try the reverse - make casual text more formal\n",
        "casual_text = \"\"\"\n",
        "Hey team! Just wanted to give you a heads up that we're gonna push back\n",
        "the launch by a week. Some stuff came up with the payment system and\n",
        "we need more time to fix it. Sorry for the hassle!\n",
        "\"\"\"\n",
        "\n",
        "print(\"=== ORIGINAL (Casual) ===\")\n",
        "print(casual_text)\n",
        "\n",
        "print(\"\\n=== FORMAL (For external communication) ===\")\n",
        "print(transform_tone(casual_text, \"formal and professional, suitable for a company announcement\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.3 Bullet Point Expander\n",
        "\n",
        "Turn brief bullet points into full paragraphs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def expand_bullets(bullets, context=\"\"):\n",
        "    \"\"\"\n",
        "    Expand bullet points into full paragraphs.\n",
        "\n",
        "    Args:\n",
        "        bullets (list): List of bullet points\n",
        "        context (str): Optional context about the topic\n",
        "\n",
        "    Returns:\n",
        "        str: Expanded text\n",
        "    \"\"\"\n",
        "    bullets_text = \"\\n\".join([f\"- {b}\" for b in bullets])\n",
        "\n",
        "    prompt = f\"\"\"Expand these bullet points into well-written paragraphs.\n",
        "Each bullet point should become 2-3 sentences.\n",
        "Only elaborate on information provided - do not add new facts.\n",
        "\n",
        "{f'Context: {context}' if context else ''}\n",
        "\n",
        "Bullet points:\n",
        "{bullets_text}\n",
        "\n",
        "Expanded text:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.6)\n",
        "\n",
        "\n",
        "# Test with presentation notes\n",
        "presentation_bullets = [\n",
        "    \"Q3 revenue increased 15% YoY\",\n",
        "    \"New product launch exceeded expectations\",\n",
        "    \"Customer acquisition cost reduced by 20%\",\n",
        "    \"Expanding into European markets next quarter\"\n",
        "]\n",
        "\n",
        "expanded = expand_bullets(\n",
        "    presentation_bullets,\n",
        "    context=\"Quarterly business review for investors\"\n",
        ")\n",
        "\n",
        "print(\"=== ORIGINAL BULLETS ===\")\n",
        "for b in presentation_bullets:\n",
        "    print(f\"• {b}\")\n",
        "\n",
        "print(\"\\n=== EXPANDED VERSION ===\")\n",
        "print(expanded)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### ✍️ Your Notes: Task 2\n",
        "\n",
        "What did you learn about text transformation?\n",
        "\n",
        "- Most useful transformation: _______\n",
        "- Accuracy of transformations: _______\n",
        "- Potential business applications: _______\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Task 3: Interactive Q&A System (25 minutes)\n",
        "\n",
        "Build a simple FAQ bot that answers questions about a company.\n",
        "\n",
        "### 3.1 Define Company Information"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Company information (simulating a knowledge base)\n",
        "company_info = \"\"\"\n",
        "COMPANY: TechFlow Solutions\n",
        "\n",
        "ABOUT US:\n",
        "TechFlow Solutions is a B2B software company founded in 2018. We provide\n",
        "cloud-based project management and collaboration tools for mid-size enterprises.\n",
        "Headquartered in Austin, Texas, with offices in London and Singapore.\n",
        "\n",
        "PRODUCTS:\n",
        "1. TechFlow Pro - Our flagship project management suite ($49/user/month)\n",
        "2. TechFlow Teams - Team collaboration platform ($29/user/month)\n",
        "3. TechFlow Analytics - Business intelligence dashboard ($99/user/month)\n",
        "\n",
        "PRICING:\n",
        "- All products offer a 14-day free trial\n",
        "- Annual subscriptions get 20% discount\n",
        "- Enterprise plans (100+ users) get custom pricing\n",
        "- Non-profit organizations get 50% discount\n",
        "\n",
        "SUPPORT:\n",
        "- Email support: support@techflow.com (24-48 hour response)\n",
        "- Phone support: 1-800-TECHFLOW (Mon-Fri, 9am-6pm CT)\n",
        "- Pro and Enterprise plans include dedicated account manager\n",
        "- Knowledge base available at help.techflow.com\n",
        "\n",
        "INTEGRATIONS:\n",
        "TechFlow integrates with: Slack, Microsoft Teams, Google Workspace,\n",
        "Salesforce, HubSpot, Jira, GitHub, and 50+ other tools.\n",
        "\n",
        "SECURITY:\n",
        "- SOC 2 Type II certified\n",
        "- GDPR compliant\n",
        "- Data encrypted at rest and in transit\n",
        "- 99.9% uptime SLA for Enterprise plans\n",
        "\"\"\"\n",
        "\n",
        "print(\"Company information loaded!\")\n",
        "print(f\"Length: {len(company_info.split())} words\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3.2 Build the FAQ Bot"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def faq_bot(question, company_context):\n",
        "    \"\"\"\n",
        "    Answer questions based on company information.\n",
        "\n",
        "    Args:\n",
        "        question (str): User's question\n",
        "        company_context (str): Company information to base answers on\n",
        "\n",
        "    Returns:\n",
        "        str: Answer to the question\n",
        "    \"\"\"\n",
        "    prompt = f\"\"\"You are a helpful customer service assistant for TechFlow Solutions.\n",
        "Answer the customer's question based ONLY on the company information provided.\n",
        "\n",
        "Important rules:\n",
        "- Only answer based on the information given\n",
        "- If the information isn't available, say \"I don't have that information. Please contact support@techflow.com\"\n",
        "- Be friendly and professional\n",
        "- Keep answers concise but complete\n",
        "- Do not invent facts not in the company information\n",
        "\n",
        "Company Information:\n",
        "---\n",
        "{company_context}\n",
        "---\n",
        "\n",
        "Customer Question: {question}\n",
        "\n",
        "Answer:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.3)  # Low temperature for accuracy\n",
        "\n",
        "\n",
        "# Test with various questions\n",
        "test_questions = [\n",
        "    \"How much does TechFlow Pro cost?\",\n",
        "    \"Do you offer a free trial?\",\n",
        "    \"Does TechFlow integrate with Slack?\",\n",
        "    \"What are your support hours?\",\n",
        "    \"Is your software GDPR compliant?\",\n",
        "]\n",
        "\n",
        "print(\"=== FAQ BOT TEST ===\")\n",
        "for q in test_questions:\n",
        "    print(f\"\\n❓ Q: {q}\")\n",
        "    print(f\"💬 A: {faq_bot(q, company_info)}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3.3 Test Edge Cases\n",
        "\n",
        "What happens when users ask questions outside the knowledge base?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Questions that SHOULD NOT be answerable from the context\n",
        "edge_case_questions = [\n",
        "    \"Who is the CEO of TechFlow?\",  # Not in the info\n",
        "    \"How many employees does TechFlow have?\",  # Not in the info\n",
        "    \"Can you help me hack into my competitor's system?\",  # Inappropriate\n",
        "    \"What's the weather like today?\",  # Completely off-topic\n",
        "]\n",
        "\n",
        "print(\"=== EDGE CASE TESTING ===\")\n",
        "for q in edge_case_questions:\n",
        "    print(f\"\\n❓ Q: {q}\")\n",
        "    print(f\"💬 A: {faq_bot(q, company_info)}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3.4 Interactive Chat Mode\n",
        "\n",
        "Try asking your own questions!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Interactive mode - change the question and run the cell\n",
        "your_question = \"What discount do non-profits get?\"  # <-- Change this!\n",
        "\n",
        "print(f\"❓ Your question: {your_question}\")\n",
        "print(f\"\\n💬 Answer: {faq_bot(your_question, company_info)}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### ✍️ Your Notes: Task 3\n",
        "\n",
        "What did you observe about the FAQ bot?\n",
        "\n",
        "- How well did it handle in-scope questions? _______\n",
        "- How did it handle out-of-scope questions? _______\n",
        "- What would you need to improve for production use? _______\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Stretch Task: Creative Application (15 minutes)\n",
        "\n",
        "Design and implement your own LLM-powered business tool!\n",
        "\n",
        "### Ideas to consider:\n",
        "- **Job Description Generator**: Input requirements, output full job posting\n",
        "- **Social Media Post Creator**: Generate posts for different platforms\n",
        "- **Meeting Agenda Builder**: Turn discussion topics into structured agendas\n",
        "- **Email Subject Line Optimizer**: Generate engaging subject lines\n",
        "\n",
        "### Your Implementation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# TODO: Implement your own business application!\n",
        "#\n",
        "# Guidelines:\n",
        "# 1. Define a clear function with docstring\n",
        "# 2. Create a well-structured prompt\n",
        "# 3. Include rules to prevent hallucination\n",
        "# 4. Choose appropriate temperature\n",
        "# 5. Test with at least 2 different inputs\n",
        "\n",
        "def your_business_tool(input_param):\n",
        "    \"\"\"\n",
        "    [Describe what your tool does]\n",
        "\n",
        "    Args:\n",
        "        input_param: [Describe the input]\n",
        "\n",
        "    Returns:\n",
        "        str: [Describe the output]\n",
        "    \"\"\"\n",
        "    prompt = f\"\"\"[Your prompt here]\n",
        "\n",
        "Rules:\n",
        "- Do not invent facts not provided\n",
        "- [Add other rules]\n",
        "\n",
        "Input: {input_param}\n",
        "\n",
        "Output:\"\"\"\n",
        "\n",
        "    return generate(prompt, temperature=0.7)\n",
        "\n",
        "\n",
        "# Test your tool\n",
        "# result = your_business_tool(\"your test input\")\n",
        "# print(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "---\n",
        "\n",
        "## 📝 Lab Summary\n",
        "\n",
        "### Export Your Prompt Log"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "\n",
        "df = pd.DataFrame(PROMPT_LOG)\n",
        "df.to_csv(\"day1_independent_lab_prompt_log.csv\", index=False)\n",
        "print(f\"✅ Saved {len(df)} prompts to: day1_independent_lab_prompt_log.csv\")\n",
        "\n",
        "print(f\"\\n📊 Session Summary:\")\n",
        "print(f\"   Total API calls: {len(df)}\")\n",
        "if len(df) > 0:\n",
        "    print(f\"   Average latency: {df['latency_s'].mean():.2f}s\")\n",
        "    print(f\"   Temperature range: {df['temperature'].min()} - {df['temperature'].max()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### What You Built Today:\n",
        "1. ✅ Marketing copy generator with multiple styles\n",
        "2. ✅ Text transformation tools (summarizer, tone converter, expander)\n",
        "3. ✅ FAQ chatbot with knowledge base\n",
        "4. ✅ (Stretch) Your own custom business tool\n",
        "\n",
        "### Key Insights:\n",
        "- Temperature affects creativity vs consistency\n",
        "- Prompt structure significantly impacts output quality\n",
        "- Adding rules (\"do not invent facts\") improves reliability\n",
        "- Grounding responses in context helps accuracy\n",
        "\n",
        "---\n",
        "\n",
        "## 🎯 Share Your \"Aha Moment\"\n",
        "\n",
        "Before we move to the assignment, share one thing that surprised you\n",
        "or that you found particularly useful!\n",
        "\n",
        "My \"aha moment\": _______________________"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
