{
  "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": "Stop building agents like web apps: Azure Functions is becoming the serious runtime for event-driven AI work",
      "slug": "stop-building-agents-like-web-apps-azure-functions-is-becomi",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-10-21T12:42:31.943Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Stop building agents like web apps: Azure Functions is becoming the serious runtime for event-driven AI work\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation flow using Python. The focus is an event-driven AI pattern where a function validates inbound events, invokes AI behind a controlled boundary, validates structured output, and emits a downstream action instead of letting free-form text directly touch systems of record.\n",
        "\n",
        "We'll simulate the Azure Functions workflow locally so you can test the contracts, validation, correlation, observability, and failure handling before deploying anything."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas pydantic"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "from typing import Literal, List, Dict, Any\n",
        "import json\n",
        "import uuid\n",
        "import time\n",
        "from datetime import datetime\n",
        "from pprint import pprint\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reference flow\n",
        "\n",
        "The architecture starts with an event, not a chat endpoint. The function acts as the runtime boundary: it validates the event, stamps correlation, calls AI through a controlled interface, validates the structured result, and emits a downstream action.\n",
        "\n",
        "Below we capture that flow as executable Python data so the notebook stays runnable."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "reference_flow = {\n",
        "    \"flow\": [\n",
        "        \"Event Source -> Azure Function Trigger\",\n",
        "        \"Validate Event + Correlation\",\n",
        "        \"AI Service Client\",\n",
        "        \"Structured Result Validation\",\n",
        "        \"Emit Downstream Action\",\n",
        "        \"Queue / Topic / Durable Workflow / API\",\n",
        "        \"App Insights / Logs\"\n",
        "    ],\n",
        "    \"principles\": [\n",
        "        \"The event is the source of truth\",\n",
        "        \"The Function owns lifecycle, validation, logging, and routing\",\n",
        "        \"The AI component handles probabilistic reasoning\",\n",
        "        \"A downstream system decides or executes based on a structured result\"\n",
        "    ]\n",
        "}\n",
        "\n",
        "pprint(reference_flow)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Typed contracts for input and output\n",
        "\n",
        "This example defines explicit contracts before any model call exists. That keeps the action surface narrow and machine-checkable: the AI can reason within a bounded set of outcomes, while downstream systems only see deterministic fields."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "sample_event = WorkItemEvent(\n",
        "    event_id=\"evt-1001\",\n",
        "    tenant_id=\"tenant-a\",\n",
        "    content=\"Customer requested refund after duplicate charge\"\n",
        ")\n",
        "\n",
        "sample_result = AIResult(\n",
        "    category=\"review\",\n",
        "    confidence=0.91,\n",
        "    rationale=\"Financial exception detected\"\n",
        ")\n",
        "\n",
        "print(sample_event)\n",
        "print(sample_result)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validation before and after intelligence\n",
        "\n",
        "Deterministic validation does the heavy lifting around the probabilistic step. We validate inbound event payloads before classification and validate AI output before any downstream action is emitted."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "def validate_event(payload: dict) -> WorkItemEvent:\n",
        "    required = [\"event_id\", \"tenant_id\", \"content\"]\n",
        "    if any(not payload.get(k) for k in required):\n",
        "        raise ValueError(\"Missing required event fields\")\n",
        "    return WorkItemEvent(**{k: payload[k] for k in required})\n",
        "\n",
        "\n",
        "def validate_ai_result(data: dict) -> AIResult:\n",
        "    result = AIResult(**data)\n",
        "    if result.category not in {\"approve\", \"review\", \"reject\"}:\n",
        "        raise ValueError(\"Invalid category\")\n",
        "    if not 0.0 <= result.confidence <= 1.0:\n",
        "        raise ValueError(\"Confidence must be between 0 and 1\")\n",
        "    return result\n",
        "\n",
        "\n",
        "valid_payload = {\n",
        "    \"event_id\": \"evt-1002\",\n",
        "    \"tenant_id\": \"tenant-b\",\n",
        "    \"content\": \"This item was approved by manager\"\n",
        "}\n",
        "\n",
        "print(validate_event(valid_payload))\n",
        "print(validate_ai_result({\"category\": \"approve\", \"confidence\": 0.97, \"rationale\": \"Clear approval language\"}))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## AI client behind a controlled backend boundary\n",
        "\n",
        "The function should not scatter direct unmanaged model access throughout the codebase. Instead, it calls a single AI client abstraction that can later be swapped for a managed model, agent service, or API gateway-backed implementation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "class AIServiceClient:\n",
        "    def classify(self, item: WorkItemEvent) -> dict:\n",
        "        text = item.content.lower()\n",
        "        if \"refund\" in text:\n",
        "            return {\"category\": \"review\", \"confidence\": 0.91, \"rationale\": \"Financial exception detected\"}\n",
        "        if \"approved\" in text:\n",
        "            return {\"category\": \"approve\", \"confidence\": 0.97, \"rationale\": \"Clear approval language\"}\n",
        "        return {\"category\": \"reject\", \"confidence\": 0.76, \"rationale\": \"Insufficient supporting context\"}\n",
        "\n",
        "\n",
        "client = AIServiceClient()\n",
        "examples = [\n",
        "    WorkItemEvent(\"evt-1\", \"tenant-a\", \"Customer requested refund after duplicate charge\"),\n",
        "    WorkItemEvent(\"evt-2\", \"tenant-a\", \"Request was approved by supervisor\"),\n",
        "    WorkItemEvent(\"evt-3\", \"tenant-a\", \"Need help maybe sometime\")\n",
        "]\n",
        "\n",
        "for item in examples:\n",
        "    print(item.event_id, client.classify(item))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Minimal event-driven Azure Function orchestration\n",
        "\n",
        "This notebook cannot host a real Azure Function runtime, so we simulate the same orchestration logic in plain Python. The function validates the event, creates a correlation ID, invokes the AI client, validates the result, and emits a queue-style action payload."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "def validate_event(payload: dict) -> WorkItemEvent:\n",
        "    required = [\"event_id\", \"tenant_id\", \"content\"]\n",
        "    if any(not payload.get(k) for k in required):\n",
        "        raise ValueError(\"Missing required event fields\")\n",
        "    return WorkItemEvent(**{k: payload[k] for k in required})\n",
        "\n",
        "\n",
        "def validate_ai_result(data: dict) -> AIResult:\n",
        "    result = AIResult(**data)\n",
        "    if result.category not in {\"approve\", \"review\", \"reject\"}:\n",
        "        raise ValueError(\"Invalid category\")\n",
        "    if not 0.0 <= result.confidence <= 1.0:\n",
        "        raise ValueError(\"Confidence must be between 0 and 1\")\n",
        "    return result\n",
        "\n",
        "\n",
        "class AIServiceClient:\n",
        "    def classify(self, item: WorkItemEvent) -> dict:\n",
        "        text = item.content.lower()\n",
        "        if \"refund\" in text:\n",
        "            return {\"category\": \"review\", \"confidence\": 0.91, \"rationale\": \"Financial exception detected\"}\n",
        "        if \"approved\" in text:\n",
        "            return {\"category\": \"approve\", \"confidence\": 0.97, \"rationale\": \"Clear approval language\"}\n",
        "        return {\"category\": \"reject\", \"confidence\": 0.76, \"rationale\": \"Insufficient supporting context\"}\n",
        "\n",
        "\n",
        "class MockEventGridEvent:\n",
        "    def __init__(self, payload: dict):\n",
        "        self._payload = payload\n",
        "\n",
        "    def get_json(self):\n",
        "        return self._payload\n",
        "\n",
        "\n",
        "class MockQueueOut:\n",
        "    def __init__(self):\n",
        "        self.value = None\n",
        "\n",
        "    def set(self, value: str):\n",
        "        self.value = value\n",
        "\n",
        "\n",
        "def process_work_item(event: MockEventGridEvent, actions: MockQueueOut) -> None:\n",
        "    payload = validate_event(event.get_json())\n",
        "    correlation_id = str(uuid.uuid4())\n",
        "    result = validate_ai_result(AIServiceClient().classify(payload))\n",
        "    action = {\n",
        "        \"correlationId\": correlation_id,\n",
        "        \"eventId\": payload.event_id,\n",
        "        \"tenantId\": payload.tenant_id,\n",
        "        \"decision\": result.category,\n",
        "        \"confidence\": result.confidence,\n",
        "        \"reason\": result.rationale,\n",
        "    }\n",
        "    actions.set(json.dumps(action))\n",
        "\n",
        "\n",
        "mock_event = MockEventGridEvent({\n",
        "    \"event_id\": \"evt-2001\",\n",
        "    \"tenant_id\": \"tenant-x\",\n",
        "    \"content\": \"Refund requested for duplicate payment\"\n",
        "})\n",
        "mock_actions = MockQueueOut()\n",
        "process_work_item(mock_event, mock_actions)\n",
        "print(json.dumps(json.loads(mock_actions.value), indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence trace of the workflow\n",
        "\n",
        "The sequence matters more than the prompt. This cell captures the interaction trace as structured data so you can inspect the stages and verify there are two validation points: one before AI and one after AI."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence_trace = [\n",
        "    {\"from\": \"Event Source\", \"to\": \"Azure Function\", \"action\": \"Deliver event\"},\n",
        "    {\"from\": \"Azure Function\", \"to\": \"Azure Function\", \"action\": \"Validate payload\"},\n",
        "    {\"from\": \"Azure Function\", \"to\": \"Azure Function\", \"action\": \"Create correlation ID\"},\n",
        "    {\"from\": \"Azure Function\", \"to\": \"AI Client\", \"action\": \"classify(work item)\"},\n",
        "    {\"from\": \"AI Client\", \"to\": \"Azure Function\", \"action\": \"structured result\"},\n",
        "    {\"from\": \"Azure Function\", \"to\": \"Azure Function\", \"action\": \"Validate result schema\"},\n",
        "    {\"from\": \"Azure Function\", \"to\": \"Action Queue\", \"action\": \"Emit downstream action\"}\n",
        "]\n",
        "\n",
        "pd.DataFrame(sequence_trace)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Infrastructure definition as notebook strings\n",
        "\n",
        "The original post includes Bicep templates for the minimum Azure Functions runtime resources. Here we store them as Python strings so you can inspect, validate, or write them to files from the notebook."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "main_bicep = \"\"\"// main.bicep - minimal Azure Functions runtime resources for event-driven AI processing\n",
        "param location string = resourceGroup().location\n",
        "param storageName string\n",
        "param functionAppName string\n",
        "param appInsightsName string\n",
        "\n",
        "resource storage 'Microsoft.Storage/storageAccounts@2023-05-01' = {\n",
        "  name: storageName\n",
        "  location: location\n",
        "  sku: { name: 'Standard_LRS' }\n",
        "  kind: 'StorageV2'\n",
        "}\n",
        "\n",
        "resource appInsights 'Microsoft.Insights/components@2020-02-02' = {\n",
        "  name: appInsightsName\n",
        "  location: location\n",
        "  kind: 'web'\n",
        "  properties: { Application_Type: 'web' }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "functionapp_bicep = \"\"\"// functionapp.bicep - app settings reference config and managed identity instead of source-code secrets\n",
        "param location string = resourceGroup().location\n",
        "param functionAppName string\n",
        "param storageName string\n",
        "param appInsightsName string\n",
        "\n",
        "resource plan 'Microsoft.Web/serverfarms@2022-09-01' = {\n",
        "  name: '${functionAppName}-plan'\n",
        "  location: location\n",
        "  sku: { name: 'Y1', tier: 'Dynamic' }\n",
        "}\n",
        "\n",
        "resource app 'Microsoft.Web/sites@2022-09-01' = {\n",
        "  name: functionAppName\n",
        "  location: location\n",
        "  kind: 'functionapp'\n",
        "  identity: { type: 'SystemAssigned' }\n",
        "  properties: {\n",
        "    serverFarmId: plan.id\n",
        "    siteConfig: {\n",
        "      appSettings: [\n",
        "        { name: 'FUNCTIONS_WORKER_RUNTIME', value: 'python' }\n",
        "        { name: 'AzureWebJobsStorage__accountName', value: storageName }\n",
        "        { name: 'APPLICATIONINSIGHTS_CONNECTION_STRING', value: 'configured-at-deploy-time' }\n",
        "        { name: 'AI_ENDPOINT', value: 'set-per-environment' }\n",
        "      ]\n",
        "    }\n",
        "  }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "print(main_bicep)\n",
        "print(functionapp_bicep)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required environment variables and configuration\n",
        "\n",
        "For a real deployment, keep configuration and identity outside the code.\n",
        "\n",
        "Required values:\n",
        "- `AI_ENDPOINT`\n",
        "- `KEY_VAULT_URI`\n",
        "- `APPLICATIONINSIGHTS_CONNECTION_STRING`\n",
        "- `AzureWebJobsStorage` or equivalent storage configuration\n",
        "- Managed identity or secret references for any AI backend credentials\n",
        "\n",
        "Do not place API keys in source code, templates, prompts, or logs."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Deployment and configuration scripts as notebook strings\n",
        "\n",
        "The post uses PowerShell to deploy infrastructure and then apply environment-specific settings. We keep those scripts as strings here so they can be reviewed or exported without requiring PowerShell execution inside the notebook."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "deploy_ps1 = r'''# deploy.ps1 - create resource group and deploy prerequisites with environment-specific parameters\n",
        "param(\n",
        "  [string]$Location = \"eastus\",\n",
        "  [string]$ResourceGroup = \"rg-agent-runtime-dev\",\n",
        "  [string]$StorageName = \"stagentruntimedev01\",\n",
        "  [string]$FunctionAppName = \"func-agent-runtime-dev\",\n",
        "  [string]$AppInsightsName = \"appi-agent-runtime-dev\"\n",
        ")\n",
        "\n",
        "az group create --name $ResourceGroup --location $Location\n",
        "az deployment group create `\n",
        "  --resource-group $ResourceGroup `\n",
        "  --template-file .\\main.bicep `\n",
        "  --parameters storageName=$StorageName functionAppName=$FunctionAppName appInsightsName=$AppInsightsName\n",
        "'''\n",
        "\n",
        "config_ps1 = r'''# config.ps1 - apply environment-specific settings without committing secrets to source control\n",
        "param(\n",
        "  [string]$ResourceGroup = \"rg-agent-runtime-dev\",\n",
        "  [string]$FunctionAppName = \"func-agent-runtime-dev\"\n",
        ")\n",
        "\n",
        "$aiEndpoint = \"https://my-ai-dev.openai.azure.com/\"\n",
        "$keyVaultUri = \"https://kv-agent-dev.vault.azure.net/\"\n",
        "\n",
        "az functionapp identity assign --name $FunctionAppName --resource-group $ResourceGroup\n",
        "az functionapp config appsettings set `\n",
        "  --name $FunctionAppName `\n",
        "  --resource-group $ResourceGroup `\n",
        "  --settings AI_ENDPOINT=$aiEndpoint KEY_VAULT_URI=$keyVaultUri\n",
        "\n",
        "# Store secrets in Key Vault or use managed identity; do not place API keys in code or templates.\n",
        "'''\n",
        "\n",
        "print(deploy_ps1)\n",
        "print(config_ps1)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Hands-on validation: run multiple events through the pipeline\n",
        "\n",
        "Now we validate the pattern with several sample events. This demonstrates how one event type can be processed consistently into structured downstream actions with correlation IDs."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "def validate_event(payload: dict) -> WorkItemEvent:\n",
        "    required = [\"event_id\", \"tenant_id\", \"content\"]\n",
        "    if any(not payload.get(k) for k in required):\n",
        "        raise ValueError(\"Missing required event fields\")\n",
        "    return WorkItemEvent(**{k: payload[k] for k in required})\n",
        "\n",
        "\n",
        "def validate_ai_result(data: dict) -> AIResult:\n",
        "    result = AIResult(**data)\n",
        "    if result.category not in {\"approve\", \"review\", \"reject\"}:\n",
        "        raise ValueError(\"Invalid category\")\n",
        "    if not 0.0 <= result.confidence <= 1.0:\n",
        "        raise ValueError(\"Confidence must be between 0 and 1\")\n",
        "    return result\n",
        "\n",
        "\n",
        "class AIServiceClient:\n",
        "    def classify(self, item: WorkItemEvent) -> dict:\n",
        "        text = item.content.lower()\n",
        "        if \"refund\" in text:\n",
        "            return {\"category\": \"review\", \"confidence\": 0.91, \"rationale\": \"Financial exception detected\"}\n",
        "        if \"approved\" in text:\n",
        "            return {\"category\": \"approve\", \"confidence\": 0.97, \"rationale\": \"Clear approval language\"}\n",
        "        return {\"category\": \"reject\", \"confidence\": 0.76, \"rationale\": \"Insufficient supporting context\"}\n",
        "\n",
        "\n",
        "def process_payload(payload: dict) -> dict:\n",
        "    item = validate_event(payload)\n",
        "    correlation_id = str(uuid.uuid4())\n",
        "    result = validate_ai_result(AIServiceClient().classify(item))\n",
        "    return {\n",
        "        \"correlationId\": correlation_id,\n",
        "        \"eventId\": item.event_id,\n",
        "        \"tenantId\": item.tenant_id,\n",
        "        \"decision\": result.category,\n",
        "        \"confidence\": result.confidence,\n",
        "        \"reason\": result.rationale,\n",
        "    }\n",
        "\n",
        "\n",
        "payloads = [\n",
        "    {\"event_id\": \"evt-3001\", \"tenant_id\": \"tenant-a\", \"content\": \"Refund requested after duplicate charge\"},\n",
        "    {\"event_id\": \"evt-3002\", \"tenant_id\": \"tenant-a\", \"content\": \"This request was approved by finance\"},\n",
        "    {\"event_id\": \"evt-3003\", \"tenant_id\": \"tenant-b\", \"content\": \"Unclear request with little context\"}\n",
        "]\n",
        "\n",
        "results = [process_payload(p) for p in payloads]\n",
        "pd.DataFrame(results)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Failure handling: malformed events and invalid model output\n",
        "\n",
        "Retries are not the same as bad business events. This cell demonstrates two failure classes: malformed inbound payloads and invalid AI output. In production, these should follow different operational paths such as retry, dead-letter, quarantine, or alerting."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "def validate_event(payload: dict) -> WorkItemEvent:\n",
        "    required = [\"event_id\", \"tenant_id\", \"content\"]\n",
        "    if any(not payload.get(k) for k in required):\n",
        "        raise ValueError(\"Missing required event fields\")\n",
        "    return WorkItemEvent(**{k: payload[k] for k in required})\n",
        "\n",
        "\n",
        "def validate_ai_result(data: dict) -> AIResult:\n",
        "    result = AIResult(**data)\n",
        "    if result.category not in {\"approve\", \"review\", \"reject\"}:\n",
        "        raise ValueError(\"Invalid category\")\n",
        "    if not 0.0 <= result.confidence <= 1.0:\n",
        "        raise ValueError(\"Confidence must be between 0 and 1\")\n",
        "    return result\n",
        "\n",
        "\n",
        "bad_payload = {\"event_id\": \"evt-bad\", \"tenant_id\": \"tenant-z\"}\n",
        "invalid_ai_output = {\"category\": \"escalate\", \"confidence\": 1.2, \"rationale\": \"Not allowed by contract\"}\n",
        "\n",
        "for label, fn, arg in [\n",
        "    (\"bad event\", validate_event, bad_payload),\n",
        "    (\"bad ai output\", validate_ai_result, invalid_ai_output),\n",
        "]:\n",
        "    try:\n",
        "        fn(arg)\n",
        "    except Exception as e:\n",
        "        print(f\"{label}: {type(e).__name__}: {e}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Observability: minimum trace record\n",
        "\n",
        "A production runtime needs operational telemetry, not just a nice answer. This example captures event ID, correlation ID, tenant context, backend, outcome, latency, retry count, and downstream action status without logging sensitive raw content."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class WorkItemEvent:\n",
        "    event_id: str\n",
        "    tenant_id: str\n",
        "    content: str\n",
        "\n",
        "\n",
        "@dataclass\n",
        "class AIResult:\n",
        "    category: Literal[\"approve\", \"review\", \"reject\"]\n",
        "    confidence: float\n",
        "    rationale: str\n",
        "\n",
        "\n",
        "def validate_event(payload: dict) -> WorkItemEvent:\n",
        "    required = [\"event_id\", \"tenant_id\", \"content\"]\n",
        "    if any(not payload.get(k) for k in required):\n",
        "        raise ValueError(\"Missing required event fields\")\n",
        "    return WorkItemEvent(**{k: payload[k] for k in required})\n",
        "\n",
        "\n",
        "def validate_ai_result(data: dict) -> AIResult:\n",
        "    result = AIResult(**data)\n",
        "    if result.category not in {\"approve\", \"review\", \"reject\"}:\n",
        "        raise ValueError(\"Invalid category\")\n",
        "    if not 0.0 <= result.confidence <= 1.0:\n",
        "        raise ValueError(\"Confidence must be between 0 and 1\")\n",
        "    return result\n",
        "\n",
        "\n",
        "class AIServiceClient:\n",
        "    backend_name = \"mock-ai-gateway\"\n",
        "\n",
        "    def classify(self, item: WorkItemEvent) -> dict:\n",
        "        text = item.content.lower()\n",
        "        if \"refund\" in text:\n",
        "            return {\"category\": \"review\", \"confidence\": 0.91, \"rationale\": \"Financial exception detected\"}\n",
        "        if \"approved\" in text:\n",
        "            return {\"category\": \"approve\", \"confidence\": 0.97, \"rationale\": \"Clear approval language\"}\n",
        "        return {\"category\": \"reject\", \"confidence\": 0.76, \"rationale\": \"Insufficient supporting context\"}\n",
        "\n",
        "\n",
        "def process_with_trace(payload: dict, retry_count: int = 0) -> Dict[str, Any]:\n",
        "    start = time.time()\n",
        "    correlation_id = str(uuid.uuid4())\n",
        "    backend = AIServiceClient()\n",
        "    status = \"success\"\n",
        "    action_status = \"emitted\"\n",
        "    decision = None\n",
        "    try:\n",
        "        item = validate_event(payload)\n",
        "        result = validate_ai_result(backend.classify(item))\n",
        "        decision = result.category\n",
        "    except Exception as e:\n",
        "        status = f\"failed: {type(e).__name__}\"\n",
        "        action_status = \"not_emitted\"\n",
        "        item = payload\n",
        "    latency_ms = round((time.time() - start) * 1000, 2)\n",
        "    return {\n",
        "        \"timestamp\": datetime.utcnow().isoformat() + \"Z\",\n",
        "        \"eventId\": payload.get(\"event_id\"),\n",
        "        \"correlationId\": correlation_id,\n",
        "        \"tenantId\": payload.get(\"tenant_id\"),\n",
        "        \"invokingIdentity\": \"system-assigned-managed-identity\",\n",
        "        \"selectedAIBackend\": backend.backend_name,\n",
        "        \"policyDecision\": decision,\n",
        "        \"outcome\": status,\n",
        "        \"latencyMs\": latency_ms,\n",
        "        \"retryCount\": retry_count,\n",
        "        \"downstreamActionStatus\": action_status,\n",
        "    }\n",
        "\n",
        "\n",
        "trace_records = [\n",
        "    process_with_trace({\"event_id\": \"evt-4001\", \"tenant_id\": \"tenant-a\", \"content\": \"Refund requested\"}),\n",
        "    process_with_trace({\"event_id\": \"evt-4002\", \"tenant_id\": \"tenant-a\", \"content\": \"Approved by manager\"}),\n",
        "    process_with_trace({\"event_id\": \"evt-4003\", \"tenant_id\": \"tenant-a\"}, retry_count=1),\n",
        "]\n",
        "\n",
        "pd.DataFrame(trace_records)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Decision rule: when this runtime pattern fits\n",
        "\n",
        "Use this pattern when the source of truth is an event, deterministic validation must surround probabilistic reasoning, actions need controlled boundaries, and operations teams need visibility into retries, failures, and downstream effects.\n",
        "\n",
        "Avoid forcing it into primarily interactive session-driven web experiences where the event model is secondary."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "decision_rule = {\n",
        "    \"good_fit\": [\n",
        "        \"system starts with an event\",\n",
        "        \"downstream actions must be controlled\",\n",
        "        \"security boundaries matter\",\n",
        "        \"platform teams need visibility\",\n",
        "        \"retries and failure isolation are first-class concerns\",\n",
        "        \"AI is one stage in a larger business process\"\n",
        "    ],\n",
        "    \"bad_fit\": [\n",
        "        \"dominant requirement is an interactive web application server\",\n",
        "        \"workflow is mostly user-driven session management\",\n",
        "        \"persistent conversational UX is the primary product surface\",\n",
        "        \"event model is an afterthought\"\n",
        "    ]\n",
        "}\n",
        "\n",
        "pprint(decision_rule)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the core pattern from the post: start with one event, define explicit contracts, validate on the way in and out, keep AI behind a controlled boundary, and emit structured downstream actions with correlation and telemetry.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "1. Replace the mock AI client with a real backend behind API Management or another governed gateway.\n",
        "2. Add confidence thresholds, approval boundaries, and poison-message handling.\n",
        "3. Persist trace records to Application Insights or a data store for dashboards.\n",
        "4. Export the Bicep and PowerShell strings into files and deploy a real Azure Functions app.\n",
        "5. Extend from one event type to a small set of explicit workflows instead of building one giant agent endpoint."
      ]
    }
  ]
}