{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CS 839: Single agent vs Multi-agent\n",
    "\n",
    "**Quick in-class exercise for designing and evaluating a multi-agent workflow.**\n",
    "\n",
    "Scenario: we have four small software incidents. First, one agent diagnoses them; this is your baseline. Next, your group will create a multi-agent team using different roles and prompts.\n",
    "\n",
    "Our goal is to determine whether any improvement is worth the additional calls, tokens, and time.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plan (expect about 30 minutes)\n",
    "\n",
    "1. **5 min:** Run the single-agent baseline.\n",
    "2. **5 min:** Design two to four roles for **specialist agents** and write their prompts.\n",
    "3. **8 min:** Choose a multi-agent topology and run your first team.\n",
    "4. **7 min:** Change one design choice and run again.\n",
    "5. **5 min:** Compare accuracy and efficiency; prepare one observation to share.\n",
    "\n",
    "Please change one thing at a time in the second experiment. Otherwise it will be hard to tell why the result changed.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The mini-benchmark\n",
    "\n",
    "Each incident includes a report, labeled evidence, candidate root causes, and candidate fixes. Every workflow must return:\n",
    "\n",
    "```json\n",
    "{\n",
    "  \"case_id\": \"CACHE-01\",\n",
    "  \"root_cause\": \"A\",\n",
    "  \"best_fix\": \"A\",\n",
    "  \"evidence\": [\"E1\", \"E2\"],\n",
    "  \"justification\": \"One or two concise sentences.\"\n",
    "}\n",
    "```\n",
    "\n",
    "Each case is worth five points:\n",
    "\n",
    "- 2 points for the root cause\n",
    "- 2 points for the best fix\n",
    "- 1 point for identifying the key evidence\n",
    "\n",
    "Efficiency is measured using model calls, total tokens, and elapsed API time. The time measurement is noisy, especially because this notebook executes calls sequentially.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Setup\n",
    "\n",
    "Run these cells once. Paste your team's API key when prompted. The key is hidden and is not saved in the notebook.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"openai>=1.0\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import html\n",
    "import json\n",
    "import os\n",
    "import time\n",
    "from IPython.display import HTML, Markdown, display\n",
    "\n",
    "try:\n",
    "    from openai import OpenAI\n",
    "except ModuleNotFoundError:\n",
    "    OpenAI = None\n",
    "\n",
    "MODEL = os.getenv(\"CS839_MODEL\", \"gpt-5.6-luna\")\n",
    "SKIP_API = os.getenv(\"CS839_SKIP_API\", \"0\") == \"1\"\n",
    "\n",
    "if not os.getenv(\"OPENAI_API_KEY\") and not SKIP_API:\n",
    "    entered_key = getpass.getpass(\"Paste your team's API key (hidden): \").strip()\n",
    "    if entered_key:\n",
    "        os.environ[\"OPENAI_API_KEY\"] = entered_key\n",
    "\n",
    "if os.getenv(\"OPENAI_API_KEY\") and OpenAI is None:\n",
    "    raise RuntimeError(\"Run the installation cell, then retry this cell.\")\n",
    "\n",
    "client = OpenAI() if os.getenv(\"OPENAI_API_KEY\") and OpenAI else None\n",
    "USAGE_LOG = []\n",
    "TEAM_TRACES = {}\n",
    "\n",
    "def show_table(rows, columns=None):\n",
    "    if not rows:\n",
    "        print(\"(no rows)\")\n",
    "        return\n",
    "    columns = columns or list(rows[0])\n",
    "    header = \"\".join(\n",
    "        f\"<th style='text-align:left;padding:6px'>{html.escape(str(c))}</th>\"\n",
    "        for c in columns\n",
    "    )\n",
    "    body = \"\".join(\n",
    "        \"<tr>\" + \"\".join(\n",
    "            f\"<td style='padding:6px;border-top:1px solid #ddd'>{html.escape(str(row.get(c, '')))}</td>\"\n",
    "            for c in columns\n",
    "        ) + \"</tr>\"\n",
    "        for row in rows\n",
    "    )\n",
    "    display(HTML(f\"<table><thead><tr>{header}</tr></thead><tbody>{body}</tbody></table>\"))\n",
    "\n",
    "print(f\"Model used for every agent: {MODEL}\")\n",
    "print(\"API client ready.\" if client else \"Offline smoke-test mode: API calls return placeholders.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. The incidents\n",
    "\n",
    "All four cases belong to the same task: diagnose a software incident from incomplete but sufficient evidence. You can inspect the cases before designing your team.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CASES = [\n",
    "    {\n",
    "        \"case_id\": \"CACHE-01\",\n",
    "        \"title\": \"Labels leak between requests\",\n",
    "        \"report\": (\n",
    "            \"The /labels endpoint sometimes returns labels from an earlier request. \"\n",
    "            \"The problem appears only after the service has handled several requests.\"\n",
    "        ),\n",
    "        \"evidence\": {\n",
    "            \"E1\": \"Code: def collect_labels(items, labels=[]): labels.extend(x['label'] for x in items); return labels\",\n",
    "            \"E2\": \"Each endpoint test passes by itself; a test that calls the endpoint twice fails.\",\n",
    "            \"E3\": \"The database rows for both requests are correct.\",\n",
    "            \"E4\": \"Restarting the Python worker clears the problem temporarily.\",\n",
    "        },\n",
    "        \"causes\": {\n",
    "            \"A\": \"A mutable default list is shared across calls.\",\n",
    "            \"B\": \"The database query cache is stale.\",\n",
    "            \"C\": \"Two asynchronous requests race while reading the database.\",\n",
    "            \"D\": \"The client retries the first request.\",\n",
    "        },\n",
    "        \"fixes\": {\n",
    "            \"A\": \"Use labels=None and allocate a new list inside each call.\",\n",
    "            \"B\": \"Disable the database query cache.\",\n",
    "            \"C\": \"Place a global lock around the endpoint.\",\n",
    "            \"D\": \"Reject duplicate request IDs.\",\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"case_id\": \"TIME-02\",\n",
    "        \"title\": \"Events disappear around midnight\",\n",
    "        \"report\": (\n",
    "            \"A daily activity report misses some evening events after timestamps were migrated to UTC. \"\n",
    "            \"The web server runs in America/Chicago.\"\n",
    "        ),\n",
    "        \"evidence\": {\n",
    "            \"E1\": \"Code builds start = datetime.now().replace(hour=0, minute=0, second=0) with no timezone.\",\n",
    "            \"E2\": \"The database stores aware UTC timestamps and interprets an unzoned query timestamp as UTC.\",\n",
    "            \"E3\": \"Missing rows occurred between 7:00 PM and midnight Central on the prior calendar day.\",\n",
    "            \"E4\": \"The report contains all rows during a test run where the server timezone is UTC.\",\n",
    "        },\n",
    "        \"causes\": {\n",
    "            \"A\": \"The report mixes a naive local-day boundary with UTC timestamps.\",\n",
    "            \"B\": \"The database index cannot compare timestamp strings.\",\n",
    "            \"C\": \"Daylight-saving time corrupted stored rows.\",\n",
    "            \"D\": \"The event ingestion queue drops evening traffic.\",\n",
    "        },\n",
    "        \"fixes\": {\n",
    "            \"A\": \"Construct aware local-day bounds, convert them to UTC, and query with both bounds.\",\n",
    "            \"B\": \"Remove the timestamp index and scan the table.\",\n",
    "            \"C\": \"Subtract six hours from every stored timestamp.\",\n",
    "            \"D\": \"Increase the ingestion queue size.\",\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"case_id\": \"RETRY-03\",\n",
    "        \"title\": \"A retry produces duplicate charges\",\n",
    "        \"report\": (\n",
    "            \"A job worker occasionally charges the same customer twice. The queue is configured to retry \"\n",
    "            \"a job when the worker does not acknowledge completion.\"\n",
    "        ),\n",
    "        \"evidence\": {\n",
    "            \"E1\": \"Code charges the card, then writes a receipt, then acknowledges the queue message.\",\n",
    "            \"E2\": \"In a duplicate incident, the first charge succeeded but the receipt write timed out.\",\n",
    "            \"E3\": \"Queue logs show the same job ID delivered twice; the payment API received two requests without an idempotency key.\",\n",
    "            \"E4\": \"CPU and memory were normal, and the two attempts ran 45 seconds apart.\",\n",
    "        },\n",
    "        \"causes\": {\n",
    "            \"A\": \"A retried job repeats a non-idempotent side effect after a partial failure.\",\n",
    "            \"B\": \"Two workers process the message simultaneously because of a race.\",\n",
    "            \"C\": \"The payment API randomly duplicates successful requests.\",\n",
    "            \"D\": \"The customer submitted the checkout form twice.\",\n",
    "        },\n",
    "        \"fixes\": {\n",
    "            \"A\": \"Use a stable idempotency key and durably record/check completion before retrying the charge.\",\n",
    "            \"B\": \"Add exponential backoff but leave the charge operation unchanged.\",\n",
    "            \"C\": \"Run only one worker for the entire queue.\",\n",
    "            \"D\": \"Increase the receipt-write timeout.\",\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"case_id\": \"MODEL-04\",\n",
    "        \"title\": \"Offline model is accurate; API predictions collapse\",\n",
    "        \"report\": (\n",
    "            \"A classifier scores 91% in the offline evaluation but nearly chance in the deployed API. \"\n",
    "            \"The same model weights are used in both places.\"\n",
    "        ),\n",
    "        \"evidence\": {\n",
    "            \"E1\": \"Training saved a fitted StandardScaler next to the model artifact.\",\n",
    "            \"E2\": \"Production creates a new StandardScaler and calls fit_transform on each incoming request batch.\",\n",
    "            \"E3\": \"Most production requests contain one example, which becomes an all-zero feature vector after per-request scaling.\",\n",
    "            \"E4\": \"Loading the production model artifact into the offline evaluation reproduces 91% accuracy.\",\n",
    "        },\n",
    "        \"causes\": {\n",
    "            \"A\": \"Inference refits preprocessing instead of applying the training-time transformation.\",\n",
    "            \"B\": \"The deployed model weights are stale.\",\n",
    "            \"C\": \"The API serializes class labels in the wrong order.\",\n",
    "            \"D\": \"The classifier needs larger request batches to make predictions.\",\n",
    "        },\n",
    "        \"fixes\": {\n",
    "            \"A\": \"Load the fitted training scaler and call transform only.\",\n",
    "            \"B\": \"Retrain the classifier on production predictions.\",\n",
    "            \"C\": \"Batch requests until at least 100 examples arrive.\",\n",
    "            \"D\": \"Remove all feature scaling from training and inference immediately.\",\n",
    "        },\n",
    "    },\n",
    "]\n",
    "\n",
    "CASE_BY_ID = {case[\"case_id\"]: case for case in CASES}\n",
    "\n",
    "def format_options(options):\n",
    "    return \"\\n\".join(f\"{key}. {value}\" for key, value in options.items())\n",
    "\n",
    "def format_case(case):\n",
    "    evidence = \"\\n\".join(f\"{key}: {value}\" for key, value in case[\"evidence\"].items())\n",
    "    return f\"\"\"\n",
    "CASE: {case['case_id']} — {case['title']}\n",
    "\n",
    "REPORT\n",
    "{case['report']}\n",
    "\n",
    "EVIDENCE\n",
    "{evidence}\n",
    "\n",
    "CANDIDATE ROOT CAUSES\n",
    "{format_options(case['causes'])}\n",
    "\n",
    "CANDIDATE FIXES\n",
    "{format_options(case['fixes'])}\n",
    "\"\"\".strip()\n",
    "\n",
    "for case in CASES:\n",
    "    display(Markdown(f\"### {case['case_id']}: {case['title']}\\n\\n```text\\n{format_case(case)}\\n```\"))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "REQUIRED_KEYS = {\"case_id\", \"root_cause\", \"best_fix\", \"evidence\", \"justification\"}\n",
    "\n",
    "def normalize_prediction(result, case_id):\n",
    "    result = dict(result)\n",
    "    missing = REQUIRED_KEYS - set(result)\n",
    "    if missing:\n",
    "        raise ValueError(f\"Model omitted fields: {sorted(missing)}\")\n",
    "    result[\"case_id\"] = case_id\n",
    "    result[\"root_cause\"] = str(result[\"root_cause\"]).strip().upper()[:1]\n",
    "    result[\"best_fix\"] = str(result[\"best_fix\"]).strip().upper()[:1]\n",
    "    result[\"evidence\"] = [str(item).strip().upper() for item in result.get(\"evidence\", [])]\n",
    "    result[\"justification\"] = str(result.get(\"justification\", \"\")).strip()\n",
    "    return result\n",
    "\n",
    "def call_agent(case, role_name, role_prompt, workflow, prior_reports=None):\n",
    "    prior_reports = prior_reports or []\n",
    "    if client is None:\n",
    "        return {\n",
    "            \"case_id\": case[\"case_id\"],\n",
    "            \"root_cause\": \"?\",\n",
    "            \"best_fix\": \"?\",\n",
    "            \"evidence\": [],\n",
    "            \"justification\": \"Offline placeholder.\",\n",
    "        }\n",
    "\n",
    "    instructions = f\"\"\"\n",
    "You are {role_name}, part of a software-incident investigation.\n",
    "\n",
    "YOUR ROLE\n",
    "{role_prompt}\n",
    "\n",
    "Use only the supplied incident evidence. Select one listed root cause and one listed fix.\n",
    "Be concise. Return one JSON object with exactly these fields:\n",
    "case_id, root_cause, best_fix, evidence, justification.\n",
    "root_cause and best_fix must be option letters. evidence must be a list of evidence IDs.\n",
    "\"\"\".strip()\n",
    "\n",
    "    collaboration = \"\"\n",
    "    if prior_reports:\n",
    "        collaboration = (\n",
    "            \"\\n\\nREPORTS FROM OTHER AGENTS\\n\"\n",
    "            + json.dumps(prior_reports, indent=2)\n",
    "            + \"\\nTreat these reports as fallible advice. Resolve disagreements using the original evidence.\"\n",
    "        )\n",
    "\n",
    "    start = time.perf_counter()\n",
    "    response = client.responses.create(\n",
    "        model=MODEL,\n",
    "        instructions=instructions,\n",
    "        input=\"Return the result as JSON.\\n\\n\" + format_case(case) + collaboration,\n",
    "        text={\"format\": {\"type\": \"json_object\"}},\n",
    "        max_output_tokens=450,\n",
    "        store=False,\n",
    "    )\n",
    "    elapsed = time.perf_counter() - start\n",
    "\n",
    "    try:\n",
    "        result = normalize_prediction(json.loads(response.output_text), case[\"case_id\"])\n",
    "    except Exception as exc:\n",
    "        result = {\n",
    "            \"case_id\": case[\"case_id\"],\n",
    "            \"root_cause\": \"?\",\n",
    "            \"best_fix\": \"?\",\n",
    "            \"evidence\": [],\n",
    "            \"justification\": f\"Could not parse output: {exc}\",\n",
    "        }\n",
    "\n",
    "    usage = response.usage\n",
    "    USAGE_LOG.append({\n",
    "        \"workflow\": workflow,\n",
    "        \"case_id\": case[\"case_id\"],\n",
    "        \"agent\": role_name,\n",
    "        \"input_tokens\": usage.input_tokens if usage else 0,\n",
    "        \"output_tokens\": usage.output_tokens if usage else 0,\n",
    "        \"elapsed_seconds\": round(elapsed, 2),\n",
    "    })\n",
    "    return result\n",
    "\n",
    "def prediction_rows(predictions):\n",
    "    return [{\n",
    "        \"case\": row[\"case_id\"],\n",
    "        \"cause\": row[\"root_cause\"],\n",
    "        \"fix\": row[\"best_fix\"],\n",
    "        \"evidence\": \", \".join(row[\"evidence\"]),\n",
    "        \"justification\": row[\"justification\"],\n",
    "    } for row in predictions]\n",
    "\n",
    "print(\"Agent runner ready.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Single-agent baseline\n",
    "\n",
    "Standard approach for a single agent. It gets to see the complete case and makes the decision. Read the prompt, then run the four cases.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BASELINE_PROMPT = \"\"\"\n",
    "Act as a careful general software incident investigator. Compare every candidate\n",
    "against the evidence, avoid inventing facts, and choose the most directly supported\n",
    "root cause and fix.\n",
    "\"\"\".strip()\n",
    "\n",
    "BASELINE_RESULTS = [\n",
    "    call_agent(case, \"single_agent\", BASELINE_PROMPT, workflow=\"single\")\n",
    "    for case in CASES\n",
    "]\n",
    "\n",
    "show_table(prediction_rows(BASELINE_RESULTS))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def score_predictions(predictions):\n",
    "    # Please do not inspect or optimize against this answer key during the exercise.\n",
    "    answer_key = {\n",
    "        \"CACHE-01\": {\"root_cause\": \"A\", \"best_fix\": \"A\", \"evidence\": {\"E1\", \"E2\", \"E4\"}},\n",
    "        \"TIME-02\": {\"root_cause\": \"A\", \"best_fix\": \"A\", \"evidence\": {\"E1\", \"E2\", \"E3\", \"E4\"}},\n",
    "        \"RETRY-03\": {\"root_cause\": \"A\", \"best_fix\": \"A\", \"evidence\": {\"E1\", \"E2\", \"E3\"}},\n",
    "        \"MODEL-04\": {\"root_cause\": \"A\", \"best_fix\": \"A\", \"evidence\": {\"E1\", \"E2\", \"E3\", \"E4\"}},\n",
    "    }\n",
    "    rows = []\n",
    "    total = 0.0\n",
    "    for result in predictions:\n",
    "        truth = answer_key[result[\"case_id\"]]\n",
    "        cause_points = 2 if result[\"root_cause\"] == truth[\"root_cause\"] else 0\n",
    "        fix_points = 2 if result[\"best_fix\"] == truth[\"best_fix\"] else 0\n",
    "        supplied = set(result.get(\"evidence\", []))\n",
    "        evidence_points = len(supplied & truth[\"evidence\"]) / len(truth[\"evidence\"])\n",
    "        points = cause_points + fix_points + evidence_points\n",
    "        total += points\n",
    "        rows.append({\n",
    "            \"case\": result[\"case_id\"],\n",
    "            \"cause pts\": cause_points,\n",
    "            \"fix pts\": fix_points,\n",
    "            \"evidence pts\": round(evidence_points, 2),\n",
    "            \"total / 5\": round(points, 2),\n",
    "        })\n",
    "    return round(100 * total / (5 * len(answer_key)), 1), rows\n",
    "\n",
    "BASELINE_ACCURACY, baseline_score_rows = score_predictions(BASELINE_RESULTS)\n",
    "show_table(baseline_score_rows)\n",
    "print(f\"Single-agent accuracy: {BASELINE_ACCURACY}%\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Design your team\n",
    "\n",
    "**Your job: introduces the roles and craft every role prompt.** Try to go beyond just asking multiple agents to “solve the problem.” Give them genuinely different work or perspectives.\n",
    "\n",
    "For example, you might try:\n",
    "\n",
    "```python\n",
    "EXAMPLE_ROLES = [\n",
    "    {\n",
    "        \"name\": \"code_tracer\",\n",
    "        \"prompt\": \"Trace the relevant code and connect each state change to the observed behavior.\"\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"skeptical_reviewer\",\n",
    "        \"prompt\": \"Try to falsify the leading diagnosis and identify evidence it fails to explain.\"\n",
    "    },\n",
    "]\n",
    "```\n",
    "\n",
    "This is only an example. You may use technical specialties, different reasoning strategies, advocates for competing hypotheses, or another decomposition.\n",
    "\n",
    "Choose one topology (or you can design your own):\n",
    "\n",
    "- **`star`:** roles work independently; a coordinator sees their reports and decides. Uses `number of roles + 1` calls per case.\n",
    "- **`chain`:** roles work in order; each sees all earlier reports and may revise the answer. The last report is final. Uses `number of roles` calls per case.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "HYPOTHESIS = \"\"\"\n",
    "Replace this with one sentence predicting how your team will differ from the baseline.\n",
    "\"\"\".strip()\n",
    "\n",
    "print(\"Our hypothesis:\", HYPOTHESIS)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Replace every TODO. Use two to four roles.\n",
    "MY_ROLES = [\n",
    "    {\n",
    "        \"name\": \"role_1\",\n",
    "        \"prompt\": \"TODO: What should this agent pay attention to, and what should it produce?\",\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"role_2\",\n",
    "        \"prompt\": \"TODO: Give this agent a meaningfully different responsibility.\",\n",
    "    },\n",
    "    # Optional third or fourth role:\n",
    "    # {\"name\": \"role_3\", \"prompt\": \"...\"},\n",
    "]\n",
    "\n",
    "TOPOLOGY = \"star\"  # Choose \"star\" or \"chain\".\n",
    "\n",
    "# Used only for the star topology. Write how the coordinator should use disagreements,\n",
    "# evidence, and confidence. The coordinator sees the original case and all role reports.\n",
    "COORDINATOR_PROMPT = \"\"\"\n",
    "TODO: Write the coordinator's role and decision policy.\n",
    "\"\"\".strip()\n",
    "\n",
    "print(\"Roles:\", [role[\"name\"] for role in MY_ROLES])\n",
    "print(\"Topology:\", TOPOLOGY)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def validate_team(roles, topology, coordinator_prompt):\n",
    "    if topology not in {\"star\", \"chain\"}:\n",
    "        raise ValueError(\"TOPOLOGY must be 'star' or 'chain'.\")\n",
    "    if not 2 <= len(roles) <= 4:\n",
    "        raise ValueError(\"Use two to four roles.\")\n",
    "    names = [role[\"name\"].strip() for role in roles]\n",
    "    if len(names) != len(set(names)):\n",
    "        raise ValueError(\"Give every role a unique name.\")\n",
    "    for role in roles:\n",
    "        if not role[\"name\"].strip() or \"TODO\" in role[\"prompt\"]:\n",
    "            raise ValueError(\"Replace every role name/prompt placeholder before running.\")\n",
    "    if topology == \"star\" and \"TODO\" in coordinator_prompt:\n",
    "        raise ValueError(\"Write the coordinator prompt before running a star team.\")\n",
    "\n",
    "def run_multi_agent(cases, roles, topology, coordinator_prompt, workflow):\n",
    "    validate_team(roles, topology, coordinator_prompt)\n",
    "    predictions = []\n",
    "    traces = {}\n",
    "\n",
    "    for case in cases:\n",
    "        reports = []\n",
    "        if topology == \"star\":\n",
    "            for role in roles:\n",
    "                report = call_agent(\n",
    "                    case,\n",
    "                    role[\"name\"],\n",
    "                    role[\"prompt\"],\n",
    "                    workflow=workflow,\n",
    "                )\n",
    "                reports.append({\"agent\": role[\"name\"], \"report\": report})\n",
    "\n",
    "            final = call_agent(\n",
    "                case,\n",
    "                \"coordinator\",\n",
    "                coordinator_prompt,\n",
    "                workflow=workflow,\n",
    "                prior_reports=reports,\n",
    "            )\n",
    "        else:\n",
    "            for role in roles:\n",
    "                report = call_agent(\n",
    "                    case,\n",
    "                    role[\"name\"],\n",
    "                    role[\"prompt\"],\n",
    "                    workflow=workflow,\n",
    "                    prior_reports=reports,\n",
    "                )\n",
    "                reports.append({\"agent\": role[\"name\"], \"report\": report})\n",
    "            final = reports[-1][\"report\"]\n",
    "\n",
    "        predictions.append(final)\n",
    "        traces[case[\"case_id\"]] = reports\n",
    "\n",
    "    TEAM_TRACES[workflow] = traces\n",
    "    return predictions\n",
    "\n",
    "def inspect_team_case(workflow, case_id):\n",
    "    reports = TEAM_TRACES[workflow][case_id]\n",
    "    display(Markdown(f\"### {workflow}: {case_id}\"))\n",
    "    for item in reports:\n",
    "        display(Markdown(\n",
    "            f\"**{item['agent']}** — cause `{item['report']['root_cause']}`, \"\n",
    "            f\"fix `{item['report']['best_fix']}`\\n\\n\"\n",
    "            f\"{item['report']['justification']}\"\n",
    "        ))\n",
    "\n",
    "print(\"Multi-agent runner ready.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Run your first team\n",
    "\n",
    "If the previous cell raises an error, that is intentional: finish the role and coordinator prompts first.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MULTI_V1_RESULTS = run_multi_agent(\n",
    "    CASES,\n",
    "    roles=MY_ROLES,\n",
    "    topology=TOPOLOGY,\n",
    "    coordinator_prompt=COORDINATOR_PROMPT,\n",
    "    workflow=\"multi_v1\",\n",
    ")\n",
    "\n",
    "show_table(prediction_rows(MULTI_V1_RESULTS))\n",
    "MULTI_V1_ACCURACY, multi_v1_score_rows = score_predictions(MULTI_V1_RESULTS)\n",
    "print(f\"Multi-agent v1 accuracy: {MULTI_V1_ACCURACY}%\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Inspect one case where the agents disagreed or where the final answer surprised you.\n",
    "CASE_TO_INSPECT = \"CACHE-01\"\n",
    "inspect_team_case(\"multi_v1\", CASE_TO_INSPECT)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def workflow_summary(workflow, predictions):\n",
    "    accuracy, _ = score_predictions(predictions)\n",
    "    logs = [row for row in USAGE_LOG if row[\"workflow\"] == workflow]\n",
    "    tokens = sum(row[\"input_tokens\"] + row[\"output_tokens\"] for row in logs)\n",
    "    return {\n",
    "        \"workflow\": workflow,\n",
    "        \"accuracy (%)\": accuracy,\n",
    "        \"calls\": len(logs),\n",
    "        \"tokens\": tokens,\n",
    "        \"API time (s)\": round(sum(row[\"elapsed_seconds\"] for row in logs), 2),\n",
    "        \"accuracy / 1K tokens\": round(accuracy / (tokens / 1000), 2) if tokens else 0,\n",
    "    }\n",
    "\n",
    "show_table([\n",
    "    workflow_summary(\"single\", BASELINE_RESULTS),\n",
    "    workflow_summary(\"multi_v1\", MULTI_V1_RESULTS),\n",
    "])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Change one thing\n",
    "\n",
    "Make one controlled change:\n",
    "\n",
    "- rewrite one role prompt;\n",
    "- add or remove one role;\n",
    "- change the order of a chain;\n",
    "- switch between star and chain; or\n",
    "- change what the coordinator does with disagreement.\n",
    "\n",
    "State the change and your prediction before running it. Then edit `MY_ROLES`, `TOPOLOGY`, or `COORDINATOR_PROMPT` above and run the next cell.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CHANGE = \"\"\"\n",
    "Replace this with the one design change you made.\n",
    "\"\"\".strip()\n",
    "\n",
    "PREDICTION = \"\"\"\n",
    "Replace this with what you expect the change to do to accuracy and efficiency.\n",
    "\"\"\".strip()\n",
    "\n",
    "print(\"Change:\", CHANGE)\n",
    "print(\"Prediction:\", PREDICTION)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MULTI_V2_RESULTS = run_multi_agent(\n",
    "    CASES,\n",
    "    roles=MY_ROLES,\n",
    "    topology=TOPOLOGY,\n",
    "    coordinator_prompt=COORDINATOR_PROMPT,\n",
    "    workflow=\"multi_v2\",\n",
    ")\n",
    "\n",
    "show_table(prediction_rows(MULTI_V2_RESULTS))\n",
    "MULTI_V2_ACCURACY, multi_v2_score_rows = score_predictions(MULTI_V2_RESULTS)\n",
    "print(f\"Multi-agent v2 accuracy: {MULTI_V2_ACCURACY}%\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Compare the workflows\n",
    "\n",
    "Higher accuracy is good. Lower calls, tokens, and time are good. There may not be a single best workflow.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "COMPARISON = [\n",
    "    workflow_summary(\"single\", BASELINE_RESULTS),\n",
    "    workflow_summary(\"multi_v1\", MULTI_V1_RESULTS),\n",
    "    workflow_summary(\"multi_v2\", MULTI_V2_RESULTS),\n",
    "]\n",
    "\n",
    "show_table(COMPARISON)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Group response\n",
    "\n",
    "Be ready to report concise answers:\n",
    "\n",
    "1. Where did multiple agents help, if anywhere?\n",
    "2. Which role or interaction was redundant?\n",
    "3. Did the coordinator correct an error, preserve it, or introduce one?\n",
    "4. Was any accuracy improvement worth the additional calls and tokens?\n",
    "5. What would you test next before deploying this workflow?\n",
    "\n",
    "The important result is not that multi-agent systems always win. It is whether your roles and topology create useful diversity—and whether the benefit survives an efficiency comparison.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Stop here until the end of our discussion\n",
    "\n",
    "The next cell reveals the intended diagnoses and fixes.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SHOW_REVEAL = False  # The instructor will tell you when to change this to True.\n",
    "\n",
    "REFERENCE = [\n",
    "    {\n",
    "        \"case\": \"CACHE-01\",\n",
    "        \"cause/fix\": \"A / A\",\n",
    "        \"key point\": \"A default list is created once and reused; a fresh list per call removes the shared state.\",\n",
    "    },\n",
    "    {\n",
    "        \"case\": \"TIME-02\",\n",
    "        \"cause/fix\": \"A / A\",\n",
    "        \"key point\": \"The intended local calendar day must be represented with aware bounds and converted to UTC.\",\n",
    "    },\n",
    "    {\n",
    "        \"case\": \"RETRY-03\",\n",
    "        \"cause/fix\": \"A / A\",\n",
    "        \"key point\": \"At-least-once delivery requires an idempotent charge operation or durable completion check.\",\n",
    "    },\n",
    "    {\n",
    "        \"case\": \"MODEL-04\",\n",
    "        \"cause/fix\": \"A / A\",\n",
    "        \"key point\": \"Inference must reuse training-time preprocessing rather than fitting preprocessing on each request.\",\n",
    "    },\n",
    "]\n",
    "\n",
    "if SHOW_REVEAL:\n",
    "    show_table(REFERENCE)\n",
    "else:\n",
    "    print(\"Reveal locked. Wait for the instructor, then set SHOW_REVEAL = True.\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if USAGE_LOG:\n",
    "    display(Markdown(\"### Call-level usage\"))\n",
    "    show_table(USAGE_LOG)\n",
    "    print(\"Total input tokens:\", sum(row[\"input_tokens\"] for row in USAGE_LOG))\n",
    "    print(\"Total output tokens:\", sum(row[\"output_tokens\"] for row in USAGE_LOG))\n",
    "else:\n",
    "    print(\"No API usage recorded in this run.\")\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
