{
  "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": "Why Azure Content Understanding’s Agentic Mode Matters for Document Automation at Scale",
      "slug": "why-azure-content-understanding-s-agentic-mode-matters-for-d",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-11T21:10:54.055Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Why Azure Content Understanding’s Agentic Mode Matters for Document Automation at Scale\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow for document automation design. The focus is not OCR alone, but the operating model around uncertainty: routing, validation, bounded retries, evidence, and auditability.\n",
        "\n",
        "You will simulate a multi-pass agentic document pipeline in Python using sample extraction results, deterministic policy logic, business validation, retry selection, and audit event generation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from typing import Dict, Any, Optional\n",
        "from decimal import Decimal\n",
        "from datetime import datetime, timezone\n",
        "import json\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture overview\n",
        "\n",
        "The blog argues that the production problem is operational, not just extraction accuracy. A scalable design separates extraction from decision policy so the system can accept, validate, retry, or escalate with evidence.\n",
        "\n",
        "Below is a simple textual representation of the target architecture."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "architecture = {\n",
        "    \"Inbound document\": \"Azure Content Understanding Agentic Mode\",\n",
        "    \"Azure Content Understanding Agentic Mode\": \"Structured extraction + confidence + evidence\",\n",
        "    \"Structured extraction + confidence + evidence\": \"Application decision policy\",\n",
        "    \"Application decision policy\": {\n",
        "        \"Accept\": \"Post to ERP/CRM\",\n",
        "        \"Validate\": \"Business rule checks\",\n",
        "        \"Retry\": \"Reprocess with alternate prompt/profile\",\n",
        "        \"Human review\": \"Queue with evidence + reason codes\"\n",
        "    },\n",
        "    \"Business rule checks\": {\n",
        "        \"Pass\": \"Post to ERP/CRM\",\n",
        "        \"Fail\": \"Queue with evidence + reason codes\"\n",
        "    }\n",
        "}\n",
        "\n",
        "print(json.dumps(architecture, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Decision policy for routing extracted results\n",
        "\n",
        "This function implements the core routing layer from the blog. It converts extraction output into an operational state with reason codes and evidence, which is what makes review and audit workable."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from typing import Dict, Any\n",
        "\n",
        "def route_document(result: Dict[str, Any]) -> Dict[str, Any]:\n",
        "    conf = result.get(\"confidence\", 0.0)\n",
        "    fields = result.get(\"fields\", {})\n",
        "    evidence = result.get(\"evidence\", [])\n",
        "    missing = [k for k in (\"invoice_id\", \"vendor\", \"total\") if not fields.get(k)]\n",
        "    reasons = []\n",
        "\n",
        "    if missing:\n",
        "        reasons.append(f\"MISSING_FIELDS:{','.join(missing)}\")\n",
        "    if conf < 0.60:\n",
        "        state = \"human-review\"\n",
        "        reasons.append(\"LOW_CONFIDENCE\")\n",
        "    elif missing:\n",
        "        state = \"validate\" if conf >= 0.85 else \"human-review\"\n",
        "    elif result.get(\"attempt\", 1) < 2 and result.get(\"transient_error\"):\n",
        "        state = \"retry\"\n",
        "        reasons.append(\"TRANSIENT_EXTRACTION_ERROR\")\n",
        "    else:\n",
        "        state = \"accept\"\n",
        "\n",
        "    return {\n",
        "        \"state\": state,\n",
        "        \"reason_codes\": reasons,\n",
        "        \"evidence\": evidence[:3],\n",
        "        \"document_id\": result[\"document_id\"]\n",
        "    }\n",
        "\n",
        "sample_results = [\n",
        "    {\n",
        "        \"document_id\": \"inv-1001\",\n",
        "        \"confidence\": 0.93,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\"invoice_id\": \"1001\", \"vendor\": \"Contoso\", \"total\": \"104.92\"},\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Invoice #1001\"}, {\"page\": 1, \"snippet\": \"Total 104.92\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-1002\",\n",
        "        \"confidence\": 0.88,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\"invoice_id\": \"1002\", \"vendor\": \"\", \"total\": \"88.10\"},\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Invoice #1002\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-1003\",\n",
        "        \"confidence\": 0.52,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\"invoice_id\": \"\", \"vendor\": \"Northwind\", \"total\": \"19.99\"},\n",
        "        \"evidence\": [{\"page\": 2, \"snippet\": \"Total Due 19.99\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-1004\",\n",
        "        \"confidence\": 0.91,\n",
        "        \"attempt\": 1,\n",
        "        \"transient_error\": True,\n",
        "        \"fields\": {\"invoice_id\": \"1004\", \"vendor\": \"Fabrikam\", \"total\": \"55.00\"},\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Vendor Fabrikam\"}]\n",
        "    }\n",
        "]\n",
        "\n",
        "routes = [route_document(r) for r in sample_results]\n",
        "pd.DataFrame(routes)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Business validation step\n",
        "\n",
        "Extraction alone is not enough for high-consequence workflows. This validation function checks arithmetic consistency and required date presence, turning model output into a pass/fail control with evidence."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from decimal import Decimal\n",
        "\n",
        "def validate_invoice(fields: dict) -> dict:\n",
        "    subtotal = Decimal(str(fields.get(\"subtotal\", \"0\")))\n",
        "    tax = Decimal(str(fields.get(\"tax\", \"0\")))\n",
        "    total = Decimal(str(fields.get(\"total\", \"0\")))\n",
        "    expected = subtotal + tax\n",
        "    delta = abs(expected - total)\n",
        "\n",
        "    passed = delta <= Decimal(\"0.01\") and bool(fields.get(\"invoice_date\"))\n",
        "    return {\n",
        "        \"passed\": passed,\n",
        "        \"reason_codes\": [] if passed else [\"TOTAL_MISMATCH_OR_DATE_MISSING\"],\n",
        "        \"evidence\": [\n",
        "            {\"check\": \"math\", \"expected_total\": str(expected), \"actual_total\": str(total)},\n",
        "            {\"check\": \"invoice_date_present\", \"value\": bool(fields.get(\"invoice_date\"))},\n",
        "        ],\n",
        "    }\n",
        "\n",
        "validation_samples = [\n",
        "    {\n",
        "        \"invoice_id\": \"1001\",\n",
        "        \"subtotal\": \"100.00\",\n",
        "        \"tax\": \"4.92\",\n",
        "        \"total\": \"104.92\",\n",
        "        \"invoice_date\": \"2026-01-15\"\n",
        "    },\n",
        "    {\n",
        "        \"invoice_id\": \"1002\",\n",
        "        \"subtotal\": \"80.00\",\n",
        "        \"tax\": \"8.10\",\n",
        "        \"total\": \"90.10\",\n",
        "        \"invoice_date\": \"2026-01-15\"\n",
        "    },\n",
        "    {\n",
        "        \"invoice_id\": \"1003\",\n",
        "        \"subtotal\": \"19.99\",\n",
        "        \"tax\": \"0.00\",\n",
        "        \"total\": \"19.99\",\n",
        "        \"invoice_date\": \"\"\n",
        "    }\n",
        "]\n",
        "\n",
        "validation_results = [validate_invoice(x) for x in validation_samples]\n",
        "pd.DataFrame([\n",
        "    {\n",
        "        \"invoice_id\": s[\"invoice_id\"],\n",
        "        \"passed\": v[\"passed\"],\n",
        "        \"reason_codes\": \", \".join(v[\"reason_codes\"]),\n",
        "        \"evidence\": json.dumps(v[\"evidence\"])\n",
        "    }\n",
        "    for s, v in zip(validation_samples, validation_results)\n",
        "])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Retry profile selection\n",
        "\n",
        "A multi-pass workflow should not retry blindly. This function chooses a bounded alternate profile based on failure patterns such as low confidence, missing fields, or receipt-like layouts."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def choose_retry_profile(route: dict, fields: dict) -> dict:\n",
        "    reasons = set(route.get(\"reason_codes\", []))\n",
        "    if \"LOW_CONFIDENCE\" in reasons:\n",
        "        return {\"profile\": \"high-accuracy\", \"max_pages\": 10, \"ocr_hint\": \"dense-text\"}\n",
        "    if any(code.startswith(\"MISSING_FIELDS\") for code in reasons):\n",
        "        return {\"profile\": \"targeted-fields\", \"focus_fields\": [\"invoice_id\", \"vendor\", \"total\"]}\n",
        "    if fields.get(\"document_type\") == \"receipt\":\n",
        "        return {\"profile\": \"receipt-layout\", \"currency_normalization\": True}\n",
        "    return {\"profile\": \"default\", \"max_pages\": 5}\n",
        "\n",
        "retry_examples = []\n",
        "for result in sample_results:\n",
        "    route = route_document(result)\n",
        "    retry_examples.append({\n",
        "        \"document_id\": result[\"document_id\"],\n",
        "        \"state\": route[\"state\"],\n",
        "        \"reason_codes\": route[\"reason_codes\"],\n",
        "        \"retry_profile\": choose_retry_profile(route, result.get(\"fields\", {}))\n",
        "    })\n",
        "\n",
        "pd.DataFrame([\n",
        "    {\n",
        "        \"document_id\": x[\"document_id\"],\n",
        "        \"state\": x[\"state\"],\n",
        "        \"reason_codes\": \", \".join(x[\"reason_codes\"]),\n",
        "        \"retry_profile\": json.dumps(x[\"retry_profile\"])\n",
        "    }\n",
        "    for x in retry_examples\n",
        "])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required environment variables for Azure integration\n",
        "\n",
        "If you connect this notebook to real Azure services, you will typically need environment variables such as:\n",
        "\n",
        "- CONTENT_UNDERSTANDING_ENDPOINT\n",
        "- AZURE_CLIENT_ID\n",
        "- AZURE_TENANT_ID\n",
        "- AZURE_CLIENT_SECRET\n",
        "- STORAGE_ACCOUNT_URL\n",
        "- REVIEW_QUEUE_NAME\n",
        "\n",
        "The examples in this notebook use simulated data, so no secrets are required to run them."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Minimal audit record generation\n",
        "\n",
        "The blog emphasizes that every non-trivial decision should leave an audit trail. This function creates a compact JSON event containing state, reason codes, evidence, and optional validation output."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import json\n",
        "from datetime import datetime, timezone\n",
        "\n",
        "def build_audit_event(route: dict, validation: Optional[dict] = None) -> str:\n",
        "    event = {\n",
        "        \"timestamp_utc\": datetime.now(timezone.utc).isoformat(),\n",
        "        \"document_id\": route[\"document_id\"],\n",
        "        \"state\": route[\"state\"],\n",
        "        \"reason_codes\": route[\"reason_codes\"],\n",
        "        \"evidence\": route[\"evidence\"],\n",
        "        \"validation\": validation or {},\n",
        "    }\n",
        "    return json.dumps(event, separators=(\",\", \":\"))\n",
        "\n",
        "example_route = {\n",
        "    \"document_id\": \"inv-1042\",\n",
        "    \"state\": \"human-review\",\n",
        "    \"reason_codes\": [\"LOW_CONFIDENCE\"],\n",
        "    \"evidence\": [{\"page\": 1, \"snippet\": \"Total Due\"}]\n",
        "}\n",
        "\n",
        "print(build_audit_event(example_route))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## End-to-end simulation\n",
        "\n",
        "This final hands-on example combines routing, validation, retry selection, and audit generation into a simple control-plane simulation. It demonstrates the core point of the blog: the value comes from explicit handling of uncertainty, not just field extraction."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def process_document(result: Dict[str, Any]) -> Dict[str, Any]:\n",
        "    route = route_document(result)\n",
        "    validation = None\n",
        "    retry_profile = None\n",
        "    final_state = route[\"state\"]\n",
        "\n",
        "    if route[\"state\"] in {\"accept\", \"validate\"}:\n",
        "        validation = validate_invoice(result.get(\"fields\", {}))\n",
        "        if route[\"state\"] == \"accept\" and not validation[\"passed\"]:\n",
        "            final_state = \"human-review\"\n",
        "            route[\"reason_codes\"] = route[\"reason_codes\"] + validation[\"reason_codes\"]\n",
        "        elif route[\"state\"] == \"validate\":\n",
        "            final_state = \"accept\" if validation[\"passed\"] else \"human-review\"\n",
        "\n",
        "    if route[\"state\"] == \"retry\":\n",
        "        retry_profile = choose_retry_profile(route, result.get(\"fields\", {}))\n",
        "\n",
        "    route[\"state\"] = final_state\n",
        "    audit_event = build_audit_event(route, validation)\n",
        "\n",
        "    return {\n",
        "        \"document_id\": result[\"document_id\"],\n",
        "        \"initial_confidence\": result.get(\"confidence\"),\n",
        "        \"final_state\": final_state,\n",
        "        \"reason_codes\": route[\"reason_codes\"],\n",
        "        \"retry_profile\": retry_profile,\n",
        "        \"validation_passed\": None if validation is None else validation[\"passed\"],\n",
        "        \"audit_event\": audit_event\n",
        "    }\n",
        "\n",
        "pipeline_inputs = [\n",
        "    {\n",
        "        \"document_id\": \"inv-2001\",\n",
        "        \"confidence\": 0.95,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\n",
        "            \"invoice_id\": \"2001\",\n",
        "            \"vendor\": \"Contoso\",\n",
        "            \"total\": \"104.92\",\n",
        "            \"subtotal\": \"100.00\",\n",
        "            \"tax\": \"4.92\",\n",
        "            \"invoice_date\": \"2026-02-01\"\n",
        "        },\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Invoice 2001\"}, {\"page\": 1, \"snippet\": \"Total 104.92\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-2002\",\n",
        "        \"confidence\": 0.89,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\n",
        "            \"invoice_id\": \"2002\",\n",
        "            \"vendor\": \"\",\n",
        "            \"total\": \"88.10\",\n",
        "            \"subtotal\": \"80.00\",\n",
        "            \"tax\": \"8.10\",\n",
        "            \"invoice_date\": \"2026-02-01\"\n",
        "        },\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Invoice 2002\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-2003\",\n",
        "        \"confidence\": 0.58,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\n",
        "            \"invoice_id\": \"\",\n",
        "            \"vendor\": \"Northwind\",\n",
        "            \"total\": \"19.99\",\n",
        "            \"subtotal\": \"19.99\",\n",
        "            \"tax\": \"0.00\",\n",
        "            \"invoice_date\": \"2026-02-01\"\n",
        "        },\n",
        "        \"evidence\": [{\"page\": 2, \"snippet\": \"Total Due 19.99\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-2004\",\n",
        "        \"confidence\": 0.92,\n",
        "        \"attempt\": 1,\n",
        "        \"transient_error\": True,\n",
        "        \"fields\": {\n",
        "            \"invoice_id\": \"2004\",\n",
        "            \"vendor\": \"Fabrikam\",\n",
        "            \"total\": \"55.00\",\n",
        "            \"subtotal\": \"50.00\",\n",
        "            \"tax\": \"5.00\",\n",
        "            \"invoice_date\": \"2026-02-01\"\n",
        "        },\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Vendor Fabrikam\"}]\n",
        "    },\n",
        "    {\n",
        "        \"document_id\": \"inv-2005\",\n",
        "        \"confidence\": 0.97,\n",
        "        \"attempt\": 1,\n",
        "        \"fields\": {\n",
        "            \"invoice_id\": \"2005\",\n",
        "            \"vendor\": \"Adventure Works\",\n",
        "            \"total\": \"120.00\",\n",
        "            \"subtotal\": \"100.00\",\n",
        "            \"tax\": \"5.00\",\n",
        "            \"invoice_date\": \"2026-02-01\"\n",
        "        },\n",
        "        \"evidence\": [{\"page\": 1, \"snippet\": \"Total 120.00\"}]\n",
        "    }\n",
        "]\n",
        "\n",
        "processed = [process_document(doc) for doc in pipeline_inputs]\n",
        "summary_df = pd.DataFrame([\n",
        "    {\n",
        "        \"document_id\": p[\"document_id\"],\n",
        "        \"initial_confidence\": p[\"initial_confidence\"],\n",
        "        \"final_state\": p[\"final_state\"],\n",
        "        \"reason_codes\": \", \".join(p[\"reason_codes\"]),\n",
        "        \"validation_passed\": p[\"validation_passed\"],\n",
        "        \"retry_profile\": \"\" if p[\"retry_profile\"] is None else json.dumps(p[\"retry_profile\"])\n",
        "    }\n",
        "    for p in processed\n",
        "])\n",
        "\n",
        "summary_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence of operations\n",
        "\n",
        "The practical loop is: submit document, receive fields plus confidence and evidence, evaluate policy, then accept, validate, retry, or send to human review. The application owns orchestration, the policy owns decisioning, and the review queue should only receive bounded exceptions with context."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence = [\n",
        "    \"App -> Content Understanding: Submit document + extraction profile\",\n",
        "    \"Content Understanding -> App: Fields, confidence, evidence, trace\",\n",
        "    \"App -> Decision Policy: Evaluate result\",\n",
        "    \"Decision Policy -> App: accept / validate / retry / human-review\",\n",
        "    \"App -> Human Review Queue: Send low-confidence cases with reason codes\",\n",
        "    \"App -> Content Understanding: Retry with alternate profile when eligible\"\n",
        "]\n",
        "\n",
        "for step_no, step in enumerate(sequence, start=1):\n",
        "    print(f\"{step_no}. {step}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the central claim of the blog: enterprise document automation succeeds when uncertainty is made explicit and governable. A multi-pass agentic pattern becomes useful when it produces observable workflow behavior such as evidence-backed routing, deterministic validation, bounded retries, and auditable human escalation.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "1. Replace the simulated extraction payloads with real Azure Content Understanding responses.\n",
        "2. Add document-class-specific validation rules for invoices, claims, intake packets, or compliance evidence.\n",
        "3. Persist audit events to a durable store for traceability and incident review.\n",
        "4. Define retry budgets, review SLAs, and acceptance thresholds before scaling to more document classes.\n",
        "5. Measure downstream outcomes such as reduced manual touches, fewer bad postings, and faster turnaround time."
      ]
    }
  ]
}