{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "Meet Brain: what AI-driven Azure reliability could mean for platform operations",
      "slug": "meet-brain-what-ai-driven-azure-reliability-could-mean-for-p",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-07-06T19:28:15.704Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Meet Brain: what AI-driven Azure reliability could mean for platform operations\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow for AI-assisted Azure reliability operations. The focus is not autonomous remediation, but better incident explanation through correlation of telemetry, changes, dependencies, and ownership context so operators can act faster with confidence."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas numpy"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import json\n",
        "from datetime import datetime, timedelta\n",
        "\n",
        "import numpy as np\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Framing the operational problem\n",
        "\n",
        "The blog argues that the biggest reliability gain from AI in Azure operations is not more alerts, but better explanations. In practice, teams often already have App Service, Redis, Azure Monitor, and identity signals available; what they lack is a compact, actionable summary that connects symptoms to likely changes and dependencies.\n",
        "\n",
        "A useful mental model is:\n",
        "- symptom spike\n",
        "- recent config or deployment change\n",
        "- known dependency path\n",
        "- similarity to prior incidents\n",
        "\n",
        "The next cells simulate that workflow in Python."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 1: Lightweight incident summarization from telemetry and change events\n",
        "\n",
        "This example converts structured telemetry and recent changes into a concise human-readable summary. It demonstrates the blog's core point: compress evidence first, then let humans judge the implications."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Python: lightweight incident summarization from telemetry + change events\n",
        "telemetry = {\n",
        "    \"service\": \"checkout-api\",\n",
        "    \"window\": \"10:00-10:15 UTC\",\n",
        "    \"error_rate_pct\": 12.4,\n",
        "    \"p95_ms\": 1840,\n",
        "    \"cpu_pct\": 38\n",
        "}\n",
        "changes = [\n",
        "    {\"time\": \"09:58\", \"type\": \"deploy\", \"detail\": \"v2026.07.06.1\"},\n",
        "    {\"time\": \"10:03\", \"type\": \"config\", \"detail\": \"Redis timeout 1s -> 200ms\"}\n",
        "]\n",
        "\n",
        "summary = (\n",
        "    f\"{telemetry['service']} degraded during {telemetry['window']}: \"\n",
        "    f\"errors {telemetry['error_rate_pct']}%, p95 {telemetry['p95_ms']}ms, \"\n",
        "    f\"CPU stable at {telemetry['cpu_pct']}%. \"\n",
        "    f\"Likely correlated changes: \" +\n",
        "    \", \".join(f\"{c['time']} {c['type']} ({c['detail']})\" for c in changes)\n",
        ")\n",
        "print(summary)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 2: Build a structured AI-assistance prompt from incident context\n",
        "\n",
        "This example shows how to package incident context into a prompt-like artifact. Even without calling an LLM, this is useful because it forces teams to standardize the fields that matter most for triage: symptom, signals, and recent changes."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Python: simple AI-assisted explanation prompt built from structured ops context\n",
        "incident = {\n",
        "    \"symptom\": \"Checkout failures increased after a config change\",\n",
        "    \"signals\": [\"5xx spike\", \"latency spike\", \"no CPU saturation\"],\n",
        "    \"recent_changes\": [\"Redis timeout reduced to 200ms\", \"deployment v2026.07.06.1\"]\n",
        "}\n",
        "\n",
        "prompt = f\"\"\"\n",
        "You are an SRE assistant.\n",
        "Explain the most likely cause, confidence, and next 3 checks.\n",
        "\n",
        "Incident: {incident['symptom']}\n",
        "Signals: {\", \".join(incident['signals'])}\n",
        "Recent changes: {\", \".join(incident['recent_changes'])}\n",
        "\"\"\"\n",
        "print(prompt.strip())"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 3: Simulate Azure activity log enrichment in Python\n",
        "\n",
        "The original post included a PowerShell example for pulling Azure activity logs. Here, we recreate the same idea in Python with mock data so the notebook remains runnable anywhere. The goal is to enrich incident reasoning with recent operational changes such as deployments, configuration updates, and identity-related actions."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Python equivalent: simulate Azure activity log context for enrichment before AI triage\n",
        "activity_logs = [\n",
        "    {\n",
        "        \"EventTimestamp\": \"2026-07-06T10:04:00Z\",\n",
        "        \"ResourceGroupName\": \"rg-prod-payments\",\n",
        "        \"ResourceId\": \"/subscriptions/123/resourceGroups/rg-prod-payments/providers/Microsoft.Cache/Redis/payments-redis\",\n",
        "        \"OperationName\": \"Microsoft.Cache/Redis/write\",\n",
        "        \"Status\": \"Succeeded\",\n",
        "        \"Caller\": \"platform.engineer@contoso.com\"\n",
        "    },\n",
        "    {\n",
        "        \"EventTimestamp\": \"2026-07-06T09:58:00Z\",\n",
        "        \"ResourceGroupName\": \"rg-prod-payments\",\n",
        "        \"ResourceId\": \"/subscriptions/123/resourceGroups/rg-prod-payments/providers/Microsoft.Web/sites/checkout-api\",\n",
        "        \"OperationName\": \"Microsoft.Web/sites/deploy/action\",\n",
        "        \"Status\": \"Succeeded\",\n",
        "        \"Caller\": \"ci-cd@contoso.com\"\n",
        "    },\n",
        "    {\n",
        "        \"EventTimestamp\": \"2026-07-06T09:40:00Z\",\n",
        "        \"ResourceGroupName\": \"rg-prod-payments\",\n",
        "        \"ResourceId\": \"/subscriptions/123/resourceGroups/rg-prod-payments/providers/Microsoft.ManagedIdentity/userAssignedIdentities/payments-id\",\n",
        "        \"OperationName\": \"Microsoft.ManagedIdentity/userAssignedIdentities/assign/action\",\n",
        "        \"Status\": \"Succeeded\",\n",
        "        \"Caller\": \"identity.ops@contoso.com\"\n",
        "    }\n",
        "]\n",
        "\n",
        "logs_df = pd.DataFrame(activity_logs)\n",
        "logs_df[\"EventTimestamp\"] = pd.to_datetime(logs_df[\"EventTimestamp\"], utc=True)\n",
        "logs_df = logs_df.sort_values(\"EventTimestamp\", ascending=False).reset_index(drop=True)\n",
        "print(logs_df.head(10).to_string(index=False))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 4: Simulate resource health context as a compact payload\n",
        "\n",
        "The original PowerShell example collected VM power state and Azure Resource Health into a compact JSON payload. This Python version mirrors that pattern using mock data, which is useful for downstream summarization, triage support, and post-incident analysis."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Python equivalent: collect resource health + incident context into a compact payload\n",
        "vm = {\n",
        "    \"Name\": \"vm-checkout-01\",\n",
        "    \"Id\": \"/subscriptions/123/resourceGroups/rg-prod-payments/providers/Microsoft.Compute/virtualMachines/vm-checkout-01\",\n",
        "    \"Statuses\": [\n",
        "        {\"Code\": \"ProvisioningState/succeeded\", \"DisplayStatus\": \"Provisioning succeeded\"},\n",
        "        {\"Code\": \"PowerState/running\", \"DisplayStatus\": \"VM running\"}\n",
        "    ]\n",
        "}\n",
        "\n",
        "health = {\n",
        "    \"Properties\": {\n",
        "        \"AvailabilityState\": \"Available\",\n",
        "        \"Summary\": \"No platform-side health events detected for this resource.\"\n",
        "    }\n",
        "}\n",
        "\n",
        "power_state = next(\n",
        "    (s[\"DisplayStatus\"] for s in vm[\"Statuses\"] if s[\"Code\"].startswith(\"PowerState/\")),\n",
        "    \"Unknown\"\n",
        ")\n",
        "\n",
        "payload = {\n",
        "    \"Resource\": vm[\"Name\"],\n",
        "    \"PowerState\": power_state,\n",
        "    \"Health\": health[\"Properties\"][\"AvailabilityState\"],\n",
        "    \"Summary\": health[\"Properties\"][\"Summary\"]\n",
        "}\n",
        "\n",
        "print(json.dumps(payload, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validate the blog's thesis with a simple correlation workflow\n",
        "\n",
        "The blog emphasizes that the hard part is not collecting telemetry, but synthesizing it under pressure. The next code cell creates a small, reproducible scoring model that ranks likely contributing changes using timing and symptom alignment.\n",
        "\n",
        "This is not meant to replace operators. It is meant to produce a better starting point for human judgment."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Simple correlation scoring for incident explanation\n",
        "incident_start = datetime.fromisoformat(\"2026-07-06T10:00:00\")\n",
        "\n",
        "candidate_changes = [\n",
        "    {\n",
        "        \"time\": datetime.fromisoformat(\"2026-07-06T09:58:00\"),\n",
        "        \"type\": \"deploy\",\n",
        "        \"detail\": \"checkout-api v2026.07.06.1\",\n",
        "        \"service_match\": True,\n",
        "        \"symptom_alignment\": 0.6\n",
        "    },\n",
        "    {\n",
        "        \"time\": datetime.fromisoformat(\"2026-07-06T10:03:00\"),\n",
        "        \"type\": \"config\",\n",
        "        \"detail\": \"Redis timeout 1s -> 200ms\",\n",
        "        \"service_match\": True,\n",
        "        \"symptom_alignment\": 0.95\n",
        "    },\n",
        "    {\n",
        "        \"time\": datetime.fromisoformat(\"2026-07-06T08:30:00\"),\n",
        "        \"type\": \"policy\",\n",
        "        \"detail\": \"Tagging policy assignment updated\",\n",
        "        \"service_match\": False,\n",
        "        \"symptom_alignment\": 0.1\n",
        "    }\n",
        "]\n",
        "\n",
        "def score_change(change, incident_time):\n",
        "    minutes_delta = abs((change[\"time\"] - incident_time).total_seconds()) / 60\n",
        "    recency_score = max(0, 1 - (minutes_delta / 120))\n",
        "    service_score = 1.0 if change[\"service_match\"] else 0.2\n",
        "    alignment_score = change[\"symptom_alignment\"]\n",
        "    total = round(0.45 * recency_score + 0.25 * service_score + 0.30 * alignment_score, 3)\n",
        "    return {\n",
        "        **change,\n",
        "        \"minutes_from_incident\": round(minutes_delta, 1),\n",
        "        \"score\": total\n",
        "    }\n",
        "\n",
        "ranked = sorted(\n",
        "    [score_change(c, incident_start) for c in candidate_changes],\n",
        "    key=lambda x: x[\"score\"],\n",
        "    reverse=True\n",
        ")\n",
        "\n",
        "ranked_df = pd.DataFrame(ranked)[[\"time\", \"type\", \"detail\", \"minutes_from_incident\", \"score\"]]\n",
        "print(ranked_df.to_string(index=False))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Add ownership and runbook context\n",
        "\n",
        "A major theme in the post is that AI-assisted incident response only works if operational basics are already in place. Ownership maps, incident taxonomy, and runbooks are essential because they let a system answer practical questions such as who owns the path and what rollback or check should happen first."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Ownership and runbook enrichment\n",
        "service_catalog = {\n",
        "    \"checkout-api\": {\n",
        "        \"owner_team\": \"payments-platform\",\n",
        "        \"slack_channel\": \"#payments-ops\",\n",
        "        \"runbook\": \"RB-017 Checkout latency and dependency timeout triage\"\n",
        "    },\n",
        "    \"payments-redis\": {\n",
        "        \"owner_team\": \"shared-cache\",\n",
        "        \"slack_channel\": \"#cache-ops\",\n",
        "        \"runbook\": \"RB-042 Redis timeout and connection investigation\"\n",
        "    }\n",
        "}\n",
        "\n",
        "dependency_path = [\"checkout-api\", \"payments-redis\", \"identity-service\"]\n",
        "\n",
        "context_rows = []\n",
        "for svc in dependency_path:\n",
        "    meta = service_catalog.get(svc, {\n",
        "        \"owner_team\": \"unknown\",\n",
        "        \"slack_channel\": \"unknown\",\n",
        "        \"runbook\": \"unknown\"\n",
        "    })\n",
        "    context_rows.append({\"service\": svc, **meta})\n",
        "\n",
        "context_df = pd.DataFrame(context_rows)\n",
        "print(context_df.to_string(index=False))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Produce a human-in-the-loop incident explanation\n",
        "\n",
        "This cell combines telemetry, ranked changes, and ownership metadata into a compact explanation. It follows the blog's recommended model:\n",
        "- what likely changed\n",
        "- what services appear correlated\n",
        "- who probably owns the affected path\n",
        "- which runbook to check first\n",
        "- how confident the explanation is"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Human-in-the-loop explanation artifact\n",
        "telemetry = {\n",
        "    \"service\": \"checkout-api\",\n",
        "    \"window\": \"10:00-10:15 UTC\",\n",
        "    \"error_rate_pct\": 12.4,\n",
        "    \"p95_ms\": 1840,\n",
        "    \"cpu_pct\": 38\n",
        "}\n",
        "\n",
        "top_change = ranked[0]\n",
        "primary_owner = service_catalog[\"checkout-api\"]\n",
        "secondary_owner = service_catalog[\"payments-redis\"]\n",
        "confidence = min(0.95, round(top_change[\"score\"], 2))\n",
        "\n",
        "explanation = {\n",
        "    \"incident_summary\": (\n",
        "        f\"{telemetry['service']} degraded during {telemetry['window']} with \"\n",
        "        f\"errors at {telemetry['error_rate_pct']}% and p95 latency at {telemetry['p95_ms']}ms. \"\n",
        "        f\"CPU remained stable at {telemetry['cpu_pct']}%, reducing the likelihood of compute saturation.\"\n",
        "    ),\n",
        "    \"likely_change\": top_change[\"detail\"],\n",
        "    \"correlated_services\": [\"checkout-api\", \"payments-redis\"],\n",
        "    \"probable_owners\": [primary_owner[\"owner_team\"], secondary_owner[\"owner_team\"]],\n",
        "    \"first_runbooks\": [primary_owner[\"runbook\"], secondary_owner[\"runbook\"]],\n",
        "    \"confidence\": confidence,\n",
        "    \"audit_trail\": {\n",
        "        \"top_ranked_change\": top_change,\n",
        "        \"supporting_signals\": [\"5xx spike\", \"latency spike\", \"no CPU saturation\"]\n",
        "    }\n",
        "}\n",
        "\n",
        "print(json.dumps(explanation, indent=2, default=str))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Readiness self-assessment for AI-assisted incident response\n",
        "\n",
        "The post ends with a practical challenge: are your runbooks and ownership maps good enough to trust the machine's explanation? Use the next cell to score your team's readiness from 1 to 5 across the foundational areas called out in the article."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Simple readiness scorecard\n",
        "criteria = {\n",
        "    \"ownership_maps\": 4,\n",
        "    \"incident_taxonomy\": 3,\n",
        "    \"change_tracking\": 4,\n",
        "    \"runbook_quality\": 3,\n",
        "    \"telemetry_coverage\": 4,\n",
        "    \"human_in_loop_process\": 5\n",
        "}\n",
        "\n",
        "score_df = pd.DataFrame(\n",
        "    [{\"criterion\": k, \"score_1_to_5\": v} for k, v in criteria.items()]\n",
        ")\n",
        "average_score = round(score_df[\"score_1_to_5\"].mean(), 2)\n",
        "\n",
        "print(score_df.to_string(index=False))\n",
        "print(f\"\\nOverall readiness score: {average_score}/5\")\n",
        "\n",
        "if average_score >= 4:\n",
        "    print(\"Recommendation: pilot AI summarization and triage support now.\")\n",
        "elif average_score >= 3:\n",
        "    print(\"Recommendation: improve taxonomy and runbooks, then pilot summarization.\")\n",
        "else:\n",
        "    print(\"Recommendation: strengthen operational basics before introducing AI assistance.\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture flow from the blog\n",
        "\n",
        "The original post included a flow diagram showing how telemetry, activity logs, and resource health feed context enrichment and AI-assisted reasoning. In notebook form, the same flow can be represented as:\n",
        "\n",
        "1. Collect Azure telemetry, activity logs, and resource health.\n",
        "2. Enrich with recent changes, dependency paths, and ownership metadata.\n",
        "3. Generate an incident summary, likely cause, confidence, and next checks.\n",
        "4. Route the explanation to the platform operations team for human decision-making.\n",
        "\n",
        "This reinforces the central idea: context-aware operations, not no-hands operations."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Next Steps\n",
        "\n",
        "This notebook validated the blog's main claim that AI is most useful in Azure reliability when it explains incidents rather than replacing operators. The examples showed how to summarize telemetry, enrich with change and health context, rank likely causes, and attach ownership and runbook guidance.\n",
        "\n",
        "Suggested next steps:\n",
        "- connect these patterns to real Azure Monitor, Activity Log, and Resource Health data\n",
        "- standardize incident taxonomy and ownership metadata\n",
        "- pilot AI for summarization, triage support, and post-incident review first\n",
        "- keep humans responsible for remediation and rollback decisions\n",
        "- measure whether explanation quality reduces time to triage and time to mitigation"
      ]
    }
  ]
}