{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 🚀 Week 5 — Polish, Gradio & Publish\n",
    "### AI Trailblazers · runs on **Google Colab** · powered by **Google Gemini (free)**\n",
    "\n",
    "This is the finale. You've built an agent — now you turn it into a **shareable portfolio asset**: a clean function, a real UI anyone can click, and a published notebook you can link on a résumé or college app.\n",
    "\n",
    "| Part | You'll do | ✅ Done when |\n",
    "|---|---|---|\n",
    "| **A · Wrap it up** | One clean `ask_agent()` function | Calling `ask_agent('...')` returns an answer |\n",
    "| **B · Gradio UI** | A web app around your agent | A live UI (with a shareable link) appears |\n",
    "| **C · Publish** | Ship to Kaggle + portfolio page | You have a public link and a portfolio blurb |\n",
    "\n",
    "> Run each grey **code cell** in order with **▶️ / Shift+Enter**. Read the note above it first."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 🅰️ Part A — Setup\n",
    "### 🔑 Get your free Gemini key (once)\n",
    "1. Open **https://aistudio.google.com/apikey** → **Create API key** → copy it.\n",
    "2. Run the cells below; paste the key when asked.\n",
    "\n",
    "🔒 An API key is a password — never paste it into a public doc, chat, or GitHub."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Install everything we need this week\n",
    "!pip -q install google-genai pandas gradio"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from google import genai\n",
    "from google.genai import types\n",
    "import pandas as pd, getpass\n",
    "\n",
    "API_KEY = getpass.getpass('Paste your Gemini API key: ').strip()\n",
    "client = genai.Client(api_key=API_KEY)\n",
    "print('Client ready ✅')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Model names change, so we ask your key which models exist and pick a fast one automatically."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "model_names = [m.name for m in client.models.list()]\n",
    "flash = [m for m in model_names if 'flash' in m and 'embedding' not in m]\n",
    "MODEL = flash[0] if flash else 'models/gemini-2.5-flash'\n",
    "print('Using MODEL =', MODEL)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ✅ TEST: talk to Gemini once\n",
    "r = client.models.generate_content(model=MODEL, contents='In 5 words, why polish a project?')\n",
    "print(r.text)\n",
    "assert r.text, 'No reply — check your key/model.'\n",
    "print('\\n✅ Setup works!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 🅱️ Part A — Wrap your agent in one clean function\n",
    "Right now your agent probably lives across a few messy cells. Real projects hide that mess behind **one function** with a clear name and a good **docstring**. That's the whole 'documentation' lesson: someone should understand your code without reading every line.\n",
    "\n",
    "### The rule of a good function\n",
    "- **Clear name** — `ask_agent` says exactly what it does.\n",
    "- **Typed signature** — `question: str -> str`: takes text, returns text.\n",
    "- **Docstring** — one line saying *what*, then *args* and *returns*.\n",
    "- **Comments** — explain the *why*, not the obvious."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# A tiny tool the agent can call, so this is a real (mini) agent, not just a chat call.\n",
    "def word_count(text: str) -> int:\n",
    "    \"\"\"Count the words in some text.\"\"\"\n",
    "    return len(text.split())\n",
    "\n",
    "def ask_agent(question: str) -> str:\n",
    "    \"\"\"Answer a question using the Gemini agent, and return the reply as text.\n",
    "\n",
    "    Args:\n",
    "        question: A plain-English question from the user.\n",
    "\n",
    "    Returns:\n",
    "        The agent's answer as a string (never None — we fall back to a message).\n",
    "    \"\"\"\n",
    "    # Give the model a tool + a short persona. Auto-calling ON = the SDK runs the loop for us.\n",
    "    config = types.GenerateContentConfig(\n",
    "        system_instruction='You are a friendly, concise study helper. Answer clearly in a few sentences.',\n",
    "        tools=[word_count],  # the model may call this when a question needs it\n",
    "    )\n",
    "    resp = client.models.generate_content(model=MODEL, contents=question, config=config)\n",
    "    return resp.text or 'Sorry, I could not come up with an answer.'  # always return a string\n",
    "\n",
    "print('ask_agent is defined ✅')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "🧪 **Test:** call your function like any other Python function. One clean line in, a full answer out."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "answer = ask_agent('Explain what an AI agent is to a 12-year-old, in 3 sentences.')\n",
    "print(answer)\n",
    "assert isinstance(answer, str) and answer, 'ask_agent should return non-empty text.'\n",
    "print('\\n✅ ask_agent works!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 🅱️ Part B — Give it a face with Gradio\n",
    "Nobody wants to run your code cell by cell. **Gradio** wraps any function in a web UI in ~3 lines. You pass it your `ask_agent` function; it builds a text box, a button, and an output box for you.\n",
    "\n",
    "In Colab, `launch(share=True)` prints a **public `gradio.live` link** you can text to a friend — they use your agent in their browser, no install. (The link lasts ~72h; re-run to refresh.)\n",
    "\n",
    "> Gradio isn't built into Colab, but we already installed it in Part A (`pip install gradio`)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "\n",
    "demo = gr.Interface(\n",
    "    fn=ask_agent,                                   # the function to run on each submit\n",
    "    inputs=gr.Textbox(lines=2, label='Ask me anything', placeholder='e.g. What is a neural network?'),\n",
    "    outputs=gr.Textbox(label='Agent answer'),\n",
    "    title='🤖 My Study Agent',\n",
    "    description='Ask a question and my Gemini-powered agent will answer.',\n",
    ")\n",
    "\n",
    "demo.launch(share=True)  # share=True gives a public link you can send to anyone"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "🧪 **Test:** a UI appears **inside this cell** with a text box and a **Submit** button — type a question, click Submit, read the answer. Look in the cell output for a `Running on public URL: https://...gradio.live` link."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 🎯 YOUR TURN: make it yours.\n",
    "# 1) Change the title + description to describe YOUR project.\n",
    "# 2) Add examples so visitors have something to click (examples=[[...], [...]]).\n",
    "my_demo = gr.Interface(\n",
    "    fn=ask_agent,\n",
    "    inputs=gr.Textbox(lines=2, label='Your question'),\n",
    "    outputs=gr.Textbox(label='Answer'),\n",
    "    title='TODO: your project name',\n",
    "    description='TODO: one line about what your agent does.',\n",
    "    examples=[['What is machine learning?'], ['Give me 3 study tips.']],\n",
    ")\n",
    "my_demo.launch(share=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 🅲 Part C — Publish it (your portfolio)\n",
    "A project only counts if someone can **see** it. This part is mostly reading + doing — no code to run. Follow the checklist and you'll walk away with a **public link**.\n",
    "\n",
    "### 1 · Colab → Kaggle in 6 steps\n",
    "1. In Colab: **File → Download → Download .ipynb**. This saves your notebook file.\n",
    "2. Go to **https://www.kaggle.com/code** → **New Notebook** (free account).\n",
    "3. **File → Import Notebook** → upload the `.ipynb` you downloaded.\n",
    "4. Add a **title** and, at the top, a markdown cell that tells the story (see below).\n",
    "5. Click **Save Version → Save & Run All**, then set the notebook to **Public**.\n",
    "6. Copy the public URL — that's your shareable link. 🎉"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2 · Tell the story (markdown = your voice)\n",
    "A great notebook reads like a mini blog post. Add markdown cells in this order:\n",
    "\n",
    "| Section | What to write |\n",
    "|---|---|\n",
    "| **Problem** | What annoyed you / what you wanted to solve (1–2 sentences). |\n",
    "| **Approach** | How your agent works — tools, the loop, Gemini. |\n",
    "| **Demo** | A screenshot or the Gradio link, plus a sample question + answer. |\n",
    "| **What I learned** | 2–3 honest takeaways (this is what readers remember). |\n",
    "\n",
    "**Markdown best practices:** use `#` headings, short paragraphs, **bold** key terms, code in backticks, and one clear image if you can. White space is your friend."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3 · Make it reproducible\n",
    "If it only runs on *your* machine, it isn't finished. Reproducible = anyone can re-run it top to bottom.\n",
    "- **Pin versions** in your install cell, e.g. `!pip install google-genai==<version> gradio==<version>`.\n",
    "- **Cell order matters** — Kaggle's *Run All* runs top→bottom, so setup must come first.\n",
    "- **No secrets in the file** — keep `getpass` for the key; never paste the key into a cell.\n",
    "- **Restart & Run All once** before publishing, to prove it works from a clean start."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4 · Portfolio page template\n",
    "Drop this on a simple site (Notion, GitHub README, Google Site) — fill in the blanks:\n",
    "\n",
    "```markdown\n",
    "# <Project name>\n",
    "**One-line pitch:** <what it does, in one sentence a stranger understands>\n",
    "\n",
    "**What it does:** <2–3 sentences: the problem + how your agent solves it>\n",
    "\n",
    "**Tools used:** Python · Google Gemini (google-genai) · Gradio · Google Colab · Kaggle\n",
    "\n",
    "**Try it / see the code:** <link to your public Kaggle notebook>\n",
    "\n",
    "**What I learned:** <2–3 bullets — skills, surprises, what you'd do next>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5 · Framing it for résumés & college apps\n",
    "Adults skim. Lead with **impact and skills**, not tools. A strong one-liner beats a paragraph:\n",
    "\n",
    "> *Built and published an AI agent (Python, Google Gemini) with a live web app used by 20+ classmates; wrote the docs and shipped it public on Kaggle.*\n",
    "\n",
    "For a résumé bullet, use the pattern **Built / Used / So that**:\n",
    "- **Built** a Gemini-powered study agent with a Gradio web interface,\n",
    "- **using** Python and the google-genai SDK,\n",
    "- **so that** anyone could ask questions and get sourced answers — published publicly on Kaggle.\n",
    "\n",
    "Keep the link handy: a clickable, working demo is the single most convincing line on a teen's application."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 🎉 You shipped it — and you finished the journey!\n",
    "You turned a pile of cells into a **product**: a clean `ask_agent()` function, a **Gradio** web app with a public link, and a **published Kaggle notebook** anyone can open.\n",
    "\n",
    "**Your 4 final deliverables:**\n",
    "1. ✅ A working Colab project (your agent, documented).\n",
    "2. ✅ A public **Kaggle notebook** with the story: problem → approach → demo → learnings.\n",
    "3. ✅ A **3-minute pitch** you can give out loud.\n",
    "4. ✅ A **portfolio page** with your one-line pitch and the link.\n",
    "\n",
    "**Look how far you came:**\n",
    "- **Week 2** — built your first agent (tools + the ReAct loop).\n",
    "- **Week 3** — turned data analysis into agent tools.\n",
    "- **Week 4** — scoped and built your own project.\n",
    "- **Week 5** — polished, wrapped, and **published** it to the world.\n",
    "\n",
    "That's the full loop of a real builder: *idea → build → polish → ship → share*. Now go send someone your link. 🚀\n",
    "\n",
    "_AI Trailblazers · LearnAI · part of MillionRoots._"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "Week 5 — Polish, Gradio & Publish",
   "provenance": []
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}