{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dc7b1eec",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/bilgrami/aigp-academy/blob/main/aigp-academy/week-01-chapter-01/lab.ipynb)\n",
    "\n",
    "# Seeing AI Risks and Controls: A Hands-On Lab for AIGP Chapter 1\n",
    "\n",
    "**Chapter 1: What AI is, and why it needs governance**, AIGP Academy week 1\n",
    "\n",
    "**Goal:** Explore AI characteristics and behaviours, including probabilistic text generation, opacity and data dependency, then consider resulting risks such as inaccurate answers, unfair treatment and privacy harm [S5, S11, S26]. By comparing outputs and examining illustrative data, connect these risks to responsible AI principles and practical controls [S5, S6, S7].\n",
    "\n",
    "**Time:** about 15 minutes\n",
    "\n",
    "**Concepts used:** Probabilistic output, Opacity, Bias, Privacy and personal data, Data minimization, Explainability, Fairness, Reliability, Human oversight\n",
    "\n",
    "To run with live models, add your OpenRouter key in Colab: the key icon on the left, name it `OPENROUTER_API_KEY`, and turn on notebook access. Without a key the lab uses saved sample outputs, so every step still works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7c1bf82",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q requests==2.32.3 pandas==2.2.2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a297c23a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install required packages (run once)\n",
    "!pip install -q requests==2.32.3 pandas==2.2.2\n",
    "\n",
    "import requests\n",
    "import json\n",
    "import time\n",
    "from datetime import datetime, timezone\n",
    "import pandas as pd\n",
    "from IPython.display import display, Markdown\n",
    "\n",
    "SYNTHETIC_LABEL = '[SYNTHETIC — illustrative only, not a recorded model output]'\n",
    "display(Markdown('**Setup banner:** Offline answers and the Exercise 2 scorecards are invented teaching examples, not measurements or recorded outputs. Every canned response carries a synthetic label. Live results will differ and all three models in Exercise 1 may answer Canberra. Do not use this lab to rank vendors or audit hiring bias.'))\n",
    "print(SYNTHETIC_LABEL)\n",
    "\n",
    "# Try to get the key without printing it.\n",
    "OPENROUTER_API_KEY = None\n",
    "try:\n",
    "    from google.colab import userdata\n",
    "except ImportError as exc:\n",
    "    print(f'{type(exc).__name__}: Colab secrets are unavailable; using offline mode.')\n",
    "else:\n",
    "    try:\n",
    "        OPENROUTER_API_KEY = userdata.get('OPENROUTER_API_KEY')\n",
    "    except userdata.SecretNotFoundError as exc:\n",
    "        print(f'{type(exc).__name__}: OPENROUTER_API_KEY was not found; using offline mode.')\n",
    "    except userdata.NotebookAccessError as exc:\n",
    "        print(f'{type(exc).__name__}: Notebook access to the secret was denied; using offline mode.')\n",
    "\n",
    "USE_LIVE = isinstance(OPENROUTER_API_KEY, str) and bool(OPENROUTER_API_KEY.strip())\n",
    "\n",
    "# Pin exact model IDs, rather than a moving alias. Live availability and prices\n",
    "# are checked against the OpenRouter catalogue before any completion call [S23].\n",
    "DEFAULT_MODEL = 'openai/gpt-4.1-nano'\n",
    "COMPARISON_MODELS = [DEFAULT_MODEL, 'google/gemini-2.5-flash-lite', 'meta-llama/llama-3.1-8b-instruct']\n",
    "\n",
    "# Illustrative prices only, USD per 1M input/output tokens, not a vendor quote.\n",
    "# No catalogue retrieval is claimed for these offline placeholders.\n",
    "pricing = {\n",
    "    'openai/gpt-4.1-nano': (0.10, 0.40),\n",
    "    'google/gemini-2.5-flash-lite': (0.10, 0.40),\n",
    "    'meta-llama/llama-3.1-8b-instruct': (0.02, 0.05)\n",
    "}\n",
    "PRICES_RETRIEVED_AT = None\n",
    "CATALOGUE_VERIFIED = False\n",
    "\n",
    "if USE_LIVE:\n",
    "    try:\n",
    "        catalogue_response = requests.get('https://openrouter.ai/api/v1/models', timeout=30)\n",
    "        catalogue_response.raise_for_status()\n",
    "        catalogue = {item['id']: item for item in catalogue_response.json()['data']}\n",
    "        verified_prices = {}\n",
    "        for model in COMPARISON_MODELS:\n",
    "            if model not in catalogue:\n",
    "                raise ValueError(f'Pinned model is absent from the live catalogue: {model}')\n",
    "            rates = catalogue[model]['pricing']\n",
    "            pair = (float(rates['prompt']) * 1_000_000, float(rates['completion']) * 1_000_000)\n",
    "            if not all(0 <= rate <= 1.0 for rate in pair):\n",
    "                raise ValueError(f'Pinned model exceeds this lab low-cost limit of $1 per 1M tokens: {model}')\n",
    "            verified_prices[model] = pair\n",
    "        pricing.update(verified_prices)\n",
    "        PRICES_RETRIEVED_AT = datetime.now(timezone.utc).isoformat()\n",
    "        CATALOGUE_VERIFIED = True\n",
    "        print(f'Pinned models verified in the live catalogue [S23]. Prices retrieved: {PRICES_RETRIEVED_AT}')\n",
    "        print('Catalogue presence is not a guarantee that a provider will serve every request.')\n",
    "    except (requests.RequestException, ValueError, KeyError, TypeError) as exc:\n",
    "        USE_LIVE = False\n",
    "        print(f'{type(exc).__name__}: Live catalogue or price verification failed. No completion calls will be made; using clearly labelled offline examples. Review the pinned IDs against S23 before retrying.')\n",
    "\n",
    "# Rough upper-budget estimate for text tokens; excludes possible extra fees.\n",
    "def estimate_cost(model, num_calls, prompt_chars, max_tokens):\n",
    "    in_price, out_price = pricing[model]\n",
    "    input_tokens = prompt_chars / 4\n",
    "    return (input_tokens * in_price + max_tokens * out_price) / 1_000_000 * num_calls\n",
    "\n",
    "def print_estimate(model, num_calls, prompt_chars, max_tokens, label=None):\n",
    "    cost = estimate_cost(model, num_calls, prompt_chars, max_tokens)\n",
    "    basis = 'catalogue-price estimate' if CATALOGUE_VERIFIED else 'illustrative-price estimate; actual offline API cost is $0'\n",
    "    print(f'{label or model}: ${cost:.6f} ({basis})')\n",
    "    return cost\n",
    "\n",
    "# Record offline outputs so the final cell can check lab coverage.\n",
    "OFFLINE_RESPONSES = []\n",
    "\n",
    "def ask(model, prompt=None, temperature=0.7, max_tokens=100, canned=None, messages=None):\n",
    "    if not USE_LIVE:\n",
    "        if canned is None:\n",
    "            raise ValueError('Offline response missing. Supply a labelled illustrative response.')\n",
    "        if isinstance(canned, list):\n",
    "            if not canned:\n",
    "                raise ValueError('Offline response list exhausted. Re-run the exercise cell.')\n",
    "            text = canned.pop(0)\n",
    "        else:\n",
    "            text = canned\n",
    "        labelled = f'{SYNTHETIC_LABEL}\\n{text}'\n",
    "        OFFLINE_RESPONSES.append(labelled)\n",
    "        return labelled\n",
    "\n",
    "    request_messages = messages if messages is not None else [{'role': 'user', 'content': prompt}]\n",
    "    headers = {'Authorization': f'Bearer {OPENROUTER_API_KEY}', 'Content-Type': 'application/json'}\n",
    "    data = {'model': model, 'messages': request_messages, 'temperature': temperature, 'max_tokens': max_tokens}\n",
    "    for attempt in range(3):\n",
    "        try:\n",
    "            response = requests.post('https://openrouter.ai/api/v1/chat/completions', headers=headers, json=data, timeout=60)\n",
    "        except (requests.Timeout, requests.ConnectionError) as exc:\n",
    "            if attempt == 2:\n",
    "                raise RuntimeError(f'{type(exc).__name__}: Live request failed after three attempts. Disable USE_LIVE and rerun the exercises for labelled offline examples.') from None\n",
    "            time.sleep(2 ** attempt)\n",
    "            continue\n",
    "        if response.status_code == 429 or 500 <= response.status_code <= 599:\n",
    "            if attempt < 2:\n",
    "                time.sleep(2 ** attempt)\n",
    "                continue\n",
    "            raise RuntimeError(f'OpenRouter HTTP {response.status_code} after three attempts. Disable USE_LIVE and rerun for labelled offline examples.')\n",
    "        if not response.ok:\n",
    "            raise RuntimeError(f'OpenRouter HTTP {response.status_code}. Check access, credits and the pinned model; no automatic retry for this HTTP error.')\n",
    "        return response.json()['choices'][0]['message']['content'].strip()\n",
    "\n",
    "print(f'USE_LIVE = {USE_LIVE}')\n",
    "if not USE_LIVE:\n",
    "    print('Offline mode: all response examples are synthetic; no completion calls or charges.')\n",
    "    print('Live availability and prices have not been verified unless a retrieval timestamp appears above.')\n",
    "\n",
    "display(Markdown('''### Key terms\n",
    "- **Probabilistic:** based on probabilities rather than a guaranteed fixed answer. Generative text systems select among possible continuations [S15].\n",
    "- **Hallucination:** generated content that is incorrect or unsupported, even when it sounds confident [S11].\n",
    "- **Opacity / black box:** difficulty understanding how a system produces its outputs [S26].\n",
    "- **Data dependency:** a system’s behaviour depends on the data used to develop and operate it [S5].\n",
    "- **Pseudonymisation versus anonymisation:** pseudonymisation separates identifying information but allows re-linking with additional information. Anonymisation requires that people are no longer identifiable, considering means reasonably likely to be used [S9, Article 4(5) and Recital 26].\n",
    "- **Feature attribution:** an explanation method that estimates which inputs influenced an output. Treat this as an estimate, not necessarily a faithful causal account [S26].\n",
    "- **Disparate impact / indirect discrimination:** disparate impact is a US legal term for an apparently neutral practice that disadvantages a protected group. Indirect discrimination is a related term used in EU and other contexts. Their legal tests differ by jurisdiction; the four-fifths rule is not a universal legal threshold. In this lab, use these terms to frame questions, not to make a legal finding.\n",
    "'''))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4c7d837",
   "metadata": {},
   "source": [
    "## Exercise 1: Same prompt, different models\n",
    "\n",
    "Generative text systems produce probabilistic outputs, and their answers need verification [S15, S11]. In live mode, ask three models the same factual question. Offline, compare invented responses from Model A, Model B and Model C. The offline differences are scripted, not evidence about any product. Live results will differ and may all answer Canberra."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac53178b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare three models on the same factual question.\n",
    "models = COMPARISON_MODELS\n",
    "labels = models if USE_LIVE else ['Model A', 'Model B', 'Model C']\n",
    "prompt = 'What is the capital of Australia? Answer in one word.'\n",
    "\n",
    "# Invented teaching examples only; ask() visibly labels every response.\n",
    "canned_responses = [['Canberra'], ['Sydney'], [\"I'm not sure.\"]]\n",
    "\n",
    "# Calculate one estimate per model and their sum before the comparison loop.\n",
    "estimates = []\n",
    "for model, label in zip(models, labels):\n",
    "    estimates.append(print_estimate(model, 1, len(prompt), 10, label=label))\n",
    "print(f'Sum of estimates: ${sum(estimates):.6f}')\n",
    "if not USE_LIVE:\n",
    "    print('Actual offline API cost: $0. These examples do not rank real products.')\n",
    "\n",
    "for i, (model, label) in enumerate(zip(models, labels)):\n",
    "    print(f'\\n--- {label} ---')\n",
    "    response = ask(model, prompt, temperature=0.0, max_tokens=10, canned=canned_responses[i])\n",
    "    print(f'Answer: {response}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5351f1e4",
   "metadata": {},
   "source": [
    "**What do you notice?** What differences do you see, if any? Why would one easy factual question be insufficient to choose a model for a business decision? How would you verify the answer?\n",
    "\n",
    "*Your notes:*\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fb67a47",
   "metadata": {},
   "source": [
    "**Governance takeaway:** A fluent answer is not a guarantee of accuracy; verify generative outputs against trusted sources [S15, S11]. For this lab, propose representative tests and documented selection criteria rather than ranking models from one question. Use the current catalogue to check deployment options, not as evidence of answer quality [S23]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8014ceed",
   "metadata": {},
   "source": [
    "## Exercise 2: Bias questions from synthetic scorecards\n",
    "\n",
    "**Warning: Never use name-only candidate scoring on real applicants.** This exercise makes no hosted model calls. It uses static scorecards for explicitly fictional candidates, with identical stated qualifications. All percentages are invented illustrations, not measured probabilities or vendor results. The demonstration is not a valid bias audit and cannot establish training-data causation. Recruitment and selection AI covered by EU AI Act Annex III(4), including systems intended to analyse or filter applications or evaluate candidates, is classified as high-risk, subject to the Act's scope and Article 6 conditions and exceptions. It is not categorically prohibited [S8]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ea2bbf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Static toy example only. No prompt, hosted scoring or vendor attribution.\n",
    "print('WARNING: Do not use name-only scoring on real applicants.')\n",
    "print(SYNTHETIC_LABEL)\n",
    "print('All candidates below are fictional. Percentages are illustrative, not measured.')\n",
    "\n",
    "scorecards = [\n",
    "    {'Fictional candidate': 'Ari Example-A', 'Stated qualifications': 'Same toy profile', 'Illustrative score': '90%'},\n",
    "    {'Fictional candidate': 'Bea Example-B', 'Stated qualifications': 'Same toy profile', 'Illustrative score': '70%'},\n",
    "    {'Fictional candidate': 'Cai Example-C', 'Stated qualifications': 'Same toy profile', 'Illustrative score': '60%'},\n",
    "    {'Fictional candidate': 'Dev Example-D', 'Stated qualifications': 'Same toy profile', 'Illustrative score': '65%'}\n",
    "]\n",
    "for card in scorecards:\n",
    "    print(f\"\\n{SYNTHETIC_LABEL}\\n{card['Fictional candidate']}: {card['Illustrative score']} | {card['Stated qualifications']}\")\n",
    "print('\\nAPI cost: $0. The differences were authored for discussion, not observed.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87427494",
   "metadata": {},
   "source": [
    "**What do you notice?** In a real evaluation, what might explain differences between scores for equally qualified candidates? What evidence would help distinguish random variation, design choices, data problems or unfair treatment? Why can these authored scorecards establish none of those explanations?\n",
    "\n",
    "*Your notes:*\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbb99169",
   "metadata": {},
   "source": [
    "**Governance takeaway:** Fairness is a responsible AI principle, but invented score differences do not demonstrate discrimination or reveal a training-data cause [S5, S6]. A proposed assessment should use job-relevant evidence, suitable comparison groups, repeated tests and documented limits. Do not infer an applicant's qualifications from a name. Recruitment and selection uses within Annex III(4) require attention to the EU AI Act's high-risk rules, not an assumption that all such AI is prohibited [S8]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23df359f",
   "metadata": {},
   "source": [
    "## Exercise 3: Finding personal data in a synthetic dataset\n",
    "\n",
    "Under GDPR Article 4(1), personal data is information relating to an identified or identifiable natural person [S9]. This academy dataset is fictional and illustrative. In a real equivalent, every column linked to an identifiable person's row would be personal data, not just names and contact details. Examine which field also contains special-category health data [S9, Article 9]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ce995dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Examine a fictional, illustrative dataset. No real people are represented.\n",
    "data = {\n",
    "    'Name': ['Alice Johnson', 'Bob Smith', 'Carol Lee', 'David Brown'],\n",
    "    'Email': ['alice.johnson@example.com', 'bob.smith@example.com', 'carol.lee@example.com', 'david.brown@example.com'],\n",
    "    'Phone': ['+1 555-0101', '+1 555-0102', '+1 555-0103', '+1 555-0104'],\n",
    "    'Age': [34, 45, 28, 52],\n",
    "    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'],\n",
    "    'Medical Condition': ['Diabetes', 'Hypertension', 'Asthma', 'None']\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print('Fictional dataset: illustrative only, not records about real people.')\n",
    "display(df)\n",
    "print('\\nIn a real equivalent, all columns linked to an identifiable row are personal data. Which field is special-category health data?')\n",
    "print('No API call needed; API cost: $0.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91f6c371",
   "metadata": {},
   "source": [
    "**What do you notice?** In a real equivalent, every column linked to an identifiable row would be personal data. Which field is special-category data? Which fields are necessary for a stated purpose, and could remaining combinations still identify someone after names are removed?\n",
    "\n",
    "*Your notes:*\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ede479f",
   "metadata": {},
   "source": [
    "**Governance takeaway:** Medical Condition contains health data, a special category under GDPR Article 9. Processing a real equivalent requires an Article 6 lawful basis, an Article 9 condition and appropriate safeguards. A data protection impact assessment (DPIA) is required when Article 35 is triggered, not automatically for every dataset [S9]. Data minimisation means using only data necessary for the purpose. Pseudonymisation means data cannot be attributed to a person without separately held additional information; re-linkable pseudonymised data remains personal data. Removing names or hashing emails does not by itself anonymise a dataset. Anonymisation has a higher bar: people must no longer be identifiable considering means reasonably likely to be used [S9, Articles 4(1), 4(5), 5(1)(c) and Recital 26]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b5af4d8",
   "metadata": {},
   "source": [
    "## Exercise 4: Temperature and randomness\n",
    "\n",
    "For generative text models, temperature 0 uses greedy decoding and greatly reduces variability, but hosted APIs do not guarantee identical outputs. Higher temperatures generally allow more varied token choices. This exercise explores that setting; its offline examples are scripted illustrations, not measurements. Generative outputs still need verification [S15, S11]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64d4e3bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Explore sampling settings. Offline differences are scripted, not measured.\n",
    "prompt = \"Write a one-sentence summary of the movie 'Inception'.\"\n",
    "\n",
    "# Repeat the same existing sentence for all three temperature-0 iterations.\n",
    "canned_temp0 = [\"A thief who steals corporate secrets through dream-sharing technology is given a chance to have his criminal history erased if he can plant an idea into a target's subconscious.\"] * 3\n",
    "canned_temp1 = [\n",
    "    'A skilled thief is offered a chance to have his past crimes forgiven if he can successfully perform inception.',\n",
    "    \"In a world where technology allows entering dreams, a thief must plant an idea in a target's mind.\",\n",
    "    'A man who steals information from dreams is tasked with planting an idea instead of stealing one.'\n",
    "]\n",
    "\n",
    "print_estimate(DEFAULT_MODEL, 6, len(prompt), 50, label=DEFAULT_MODEL if USE_LIVE else 'Offline temperature illustration')\n",
    "\n",
    "temp0_outputs = []\n",
    "print('\\n--- Temperature = 0.0 (reduced variability, not a hosted reproducibility guarantee) ---')\n",
    "for i in range(3):\n",
    "    response = ask(DEFAULT_MODEL, prompt, temperature=0.0, max_tokens=50, canned=canned_temp0)\n",
    "    temp0_outputs.append(response)\n",
    "    print(f'Run {i+1}: {response}')\n",
    "\n",
    "print('\\n--- Temperature = 1.0 (more varied sampling) ---')\n",
    "for i in range(3):\n",
    "    response = ask(DEFAULT_MODEL, prompt, temperature=1.0, max_tokens=50, canned=canned_temp1)\n",
    "    print(f'Run {i+1}: {response}')\n",
    "\n",
    "if not USE_LIVE:\n",
    "    assert len(temp0_outputs) == 3 and len(set(temp0_outputs)) == 1\n",
    "    assert not canned_temp0 and not canned_temp1\n",
    "    print('Offline cell check passed: three identical temperature-0 examples and three temperature-1 examples returned without exhausting either list early.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72f0e264",
   "metadata": {},
   "source": [
    "**What do you notice?** How much variation do you see? In live mode, is there residual variation at 0.0? What would you record and test before relying on this setting? Why can a low temperature neither establish correctness nor make a high-stakes use safe by itself?\n",
    "\n",
    "*Your notes:*\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc72305d",
   "metadata": {},
   "source": [
    "**Governance takeaway:** Probabilistic generation calls for output verification, even when sampling variability is reduced [S15, S11]. A governance control may specify sampling settings alongside testing and human review. Document the chosen settings, model version, test results and review process as part of lifecycle policies and procedures [S12]. The identical offline sentences illustrate a setting; they do not prove hosted reproducibility."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e163611b",
   "metadata": {},
   "source": [
    "## Exercise 5: Opacity - asking the model to explain itself\n",
    "\n",
    "Complex AI systems can be difficult to understand, and interpretability and explainability are distinct concepts [S26]. Ask a model for an answer, then ask for an explanation in the same conversation. Check whether the arithmetic is valid without treating the generated explanation as direct access to the model's internal computation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b42c2860",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Ask a follow-up in the context of the prior answer.\n",
    "question = 'What is 15 * 7?'\n",
    "followup = 'Why did you give that answer? Give a brief arithmetic explanation that I can check.'\n",
    "\n",
    "# Illustrative examples only; ask() labels both outputs in offline mode.\n",
    "canned_answer = ['105']\n",
    "canned_explanation = ['The prior answer was 105. You can check it by splitting 15 into 10 and 5: 10 times 7 is 70, 5 times 7 is 35, and 70 plus 35 is 105.']\n",
    "\n",
    "# The second request includes the prior answer, so its final estimate is printed below.\n",
    "print_estimate(DEFAULT_MODEL, 1, len(question), 10, label=DEFAULT_MODEL if USE_LIVE else 'Offline answer illustration')\n",
    "print('Question:', question)\n",
    "answer = ask(DEFAULT_MODEL, question, temperature=0.0, max_tokens=10, canned=canned_answer)\n",
    "print('Answer:', answer)\n",
    "\n",
    "# Keep the visible synthetic label out of the assistant's conversation content.\n",
    "prior_answer = answer.removeprefix(SYNTHETIC_LABEL + '\\n') if not USE_LIVE else answer\n",
    "messages = [\n",
    "    {'role': 'user', 'content': question},\n",
    "    {'role': 'assistant', 'content': prior_answer},\n",
    "    {'role': 'user', 'content': followup}\n",
    "]\n",
    "print_estimate(DEFAULT_MODEL, 1, sum(len(message['content']) for message in messages), 100, label=DEFAULT_MODEL if USE_LIVE else 'Offline follow-up illustration')\n",
    "print('\\nFollow-up:', followup)\n",
    "explanation = ask(DEFAULT_MODEL, temperature=0.0, max_tokens=100, canned=canned_explanation, messages=messages)\n",
    "print('Explanation:', explanation)\n",
    "\n",
    "# Runtime top-to-bottom offline checks. Run all cells in order to execute them.\n",
    "if not USE_LIVE:\n",
    "    assert len(OFFLINE_RESPONSES) >= 11, 'Run Exercises 1, 4 and 5 in order before this check.'\n",
    "    assert all(item.startswith(SYNTHETIC_LABEL) for item in OFFLINE_RESPONSES)\n",
    "    assert all('No more canned responses' not in item for item in OFFLINE_RESPONSES)\n",
    "    assert len(temp0_outputs) == 3 and len(set(temp0_outputs)) == 1\n",
    "    print('Offline run checks passed: all model-response examples were labelled, all three temperature-0 outputs matched, and no No more canned responses message appeared.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee1ad0bc",
   "metadata": {},
   "source": [
    "**What do you notice?** Can you verify the arithmetic independently? Does a correct explanation establish how the system internally produced its answer? What further evidence would you need to assess opacity in a consequential application?\n",
    "\n",
    "*Your notes:*\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88471ceb",
   "metadata": {},
   "source": [
    "**Governance takeaway:** A checkable arithmetic explanation is useful, but it is not evidence that the model's internal computation followed those steps. Feature attribution estimates which inputs influenced an output and is not necessarily a faithful causal account; distinguish explanation from understanding the system itself [S26]. For in-scope high-risk EU AI Act systems, effective oversight means assigning a competent person with the authority and time to interpret outputs, override them or stop the system where appropriate [S8, Article 14]. For other uses, consider and document oversight controls suited to the context rather than treating one explanation as sufficient [S12]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ac166e8",
   "metadata": {},
   "source": [
    "## Reflection\n",
    "\n",
    "Reflect on the behaviours and characteristics explored here: How can probabilistic generation, opacity and data dependency contribute to inaccurate answers, unfair treatment or privacy harm [S5, S11, S26]? Which observations came from live calls, and which were authored illustrations? Which responsible AI principle, such as fairness, safety, privacy, transparency, accountability or human-centricity, is hardest to turn into a practical control, and why [S5, S6, S7]? What tests, documentation and responsible person would you propose for that control [S12]?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f58f3a38",
   "metadata": {},
   "source": [
    "## Your deliverable\n",
    "\n",
    "Fill in the table below with your observations from the lab. For each exercise, note one risk observed or illustrated, one proposed control, and the responsible AI principle it relates to. State whether the evidence is live or synthetic. For Exercise 2, do not report the toy percentages as measured bias. For Exercise 3, remember that all fields linked to an identifiable person are personal data; Medical Condition is health data, and removing names alone does not establish anonymisation [S9].\n",
    "\n",
    "| Exercise | Risk observed or illustrated | Control | Principle |\n",
    "|----------|-------------------------------|---------|------------|\n",
    "| 1: Model comparison | | | |\n",
    "| 2: Synthetic scorecards | | | |\n",
    "| 3: Personal data | | | |\n",
    "| 4: Temperature variation | | | |\n",
    "| 5: Explanation opacity | | | |\n",
    "\n",
    "### Sources\n",
    "- **S5:** NIST, AI Risk Management Framework 1.0. https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf\n",
    "- **S6:** OECD AI Principles. https://oecd.ai/en/ai-principles\n",
    "- **S7:** UNESCO, Recommendation on the Ethics of Artificial Intelligence. https://www.unesco.org/en/artificial-intelligence/recommendation-ethics\n",
    "- **S8:** EU AI Act, especially Article 6, Annex III(4) and Article 14. https://eur-lex.europa.eu/eli/reg/2024/1689/oj\n",
    "- **S9:** GDPR, especially Articles 4, 5, 6, 9 and 35, and Recital 26. https://eur-lex.europa.eu/eli/reg/2016/679/oj\n",
    "- **S11:** NIST, Generative Artificial Intelligence Profile. https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.600-1.pdf\n",
    "- **S12:** ISO/IEC 42001:2023, AI management system. https://www.iso.org/standard/81230.html\n",
    "- **S15:** Generative AI for Everyone. https://www.deeplearning.ai/courses/generative-ai-for-everyone/\n",
    "- **S23:** OpenRouter Models catalogue. Live availability and price retrieval occur when setup runs with a key. https://openrouter.ai/models\n",
    "- **S26:** Explainable Artificial Intelligence: Concepts, Taxonomies, Opportunities and Challenges toward Responsible AI. https://arxiv.org/abs/1910.10045"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
