Why I Skipped LLMs to Extract Data From 100,000 Wills: A System Design Story
From the publisher’s feed, collected in the ZeroLabs newsroom.
Generated by GeminiEveryone is obsessed with LLMs right now. If you look at LinkedIn, it seems like the answer to every problem is “just plug it into ChatGPT.”But I recently faced a project where “just plugging it in” would have been a disaster. I was tasked with a Proof of Concept (PoC) to perform deep data analysis on 1,000 Wills, with a goal to eventually process 100,000.In the legal world, accuracy isn’t just a goal; it’s a requirement. If an AI “hallucinates” the name of a beneficiary or misses a guardianship clause, it’s not just a bug — it’s a legal nightmare. Here is how I built a deterministic, automated pipeline that prioritized precision over hype.The Problem: “Messy” Doesn’t Even Describe ItWhen I first opened the dataset, I realized I was in trouble. These weren’t clean, digital documents. I was looking at:Old scans and JPEGs: Blurry, tilted, and full of digital “noise.”Handwriting: Notes scribbled in margins and signatures that overlapped the text.Random Templates: Every lawyer seems to have their own “special” way of writing a Will.I had a massive list of things to find (my “Schema”). I needed names, National Insurance numbers, specific gift clauses, and even “Funeral Wishes.” I also had to implement “Business Rules” — like flagging any Will where the executor was an agency, or identifying Wills that were between 10 and 35 years old.Why I Said “No” to LLMs I tested the standard generative AI route first, and it failed the “legal stress test” for two reasons:The Hallucination Factor: If a scan was fuzzy, the LLM would “helpfully” guess the name of a beneficiary. In a legal document, “guessing” is a crime.The Cost: Feeding 100,000 multi-page documents into a high-end LLM is financially draining. I needed something cheaper, faster, and more deterministic.My First Failure: Standard Document IntelligenceI started with Azure AI Document Intelligence. It’s a great tool, but I hit a wall. Standard models work best when the document follows a fixed structure (like an invoice). But every Will I had was different. The “hard-coded” nature of standard OCR couldn’t keep up with the creative ways lawyers write Wills.My Breakthrough: The “Content Understanding” ModelI decided to pivot to a Content Understanding Model on Azure.This was the “Aha!” moment. Instead of the AI just trying to read text, this model allowed me to upload my own custom JSON schema first. I basically told the AI: “Here is exactly what I am looking for. Go find it.”I started manually. I uploaded Wills and watched how the model performed. At first, the “Confidence Scores” were low. But I didn’t give up. I used the model training feature to manually “teach” the AI where to look and how to interpret specific legal phrases.This shifted the accuracy from “okay” to a massive 95% confidence score.screen shot of dummy willThe “Three-Container” ArchitectureOnce the “brain” (the model) was working, I had to build the “body” (the automation). I didn’t want to process these one by one. I wanted a system where I could just drop a folder of 10,000 Wills and go have a coffee while the system worked.I set up three containers in Azure Blob Storage:Raw Wills: This is the “Inbox.” I drop the JPEGs and PDFs here.Extracted JSON: The AI puts its raw findings here. It’s a bit messy at this stage.Curated JSON: This is the “Clean Room.” I wrote logic to refine the raw data so it matches my final database perfectly.Building the “Digital Warehouse” (SQL Server)This is the part many people skip, but it was the most important for the analysis. I needed a structured home for all this data.I created an Azure SQL Server and built a dedicated SQL Database. I didn’t just make one big table; I created columns for every single field in my schema: ClientName, WillDate, ExecutorName, MaritalStatus, and so on.By moving the data into SQL, I made it “permanent” and “searchable.” If a client asked, “How many Wills mention a charity as a beneficiary?” I could find the answer with a simple SQL query in seconds, rather than reading 1,000 PDFs.Automating the Flow with Azure FunctionsTo tie it all together, I used Azure Functions. Think of this as a “Trigger” that stays awake 24/7.Here is the flow I built:The Trigger: As soon as a file hits the “Raw Wills” folder, the Azure Function wakes up.The AI Call: It sends the Will to my trained Content Understanding model.The Extraction: It grabs the JSON output and saves it in the “Extracted” folder.The Curation: It cleans up the data (fixing date formats, etc.) and moves it to the “Curated” folder.The SQL Push: Finally, it maps that JSON data to my SQL table and saves it.This whole process happens in seconds without me touching a single button.The CodeHere is a simplified version of the logic I used to bridge the gap between the AI extraction and the SQL database:import jsonimport loggingimport osimport structimport timeimport uuidfrom datetime import datetime, timezoneimport azure.functions as funcimport pyodbcimport requestsfrom azure.identity import DefaultAzureCredentialfrom azure.storage.blob import BlobServiceClient, ContentSettingsfrom azure.storage.queue import QueueClientimport re# -----------------------------# Azure Functions app# -----------------------------app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)# -----------------------------# Helpers: Content Understanding (Foundry) REST# -----------------------------_CU_SCOPE = "https://cognitiveservices.azure.com/.default"def _get_cu_headers(content_type: str | None = None) -> dict: """ Uses your existing setting names: - If CU_KEY is set -> uses Ocp-Apim-Subscription-Key (API key auth) - Else -> uses Managed Identity via DefaultAzureCredential (Bearer token) NOTE: No variable renames needed anywhere else. """ key = os.getenv("CU_KEY") if key: headers = {"Ocp-Apim-Subscription-Key": key} else: cred = DefaultAzureCredential() token = cred.get_token(_CU_SCOPE).token headers = {"Authorization": f"Bearer {token}"} if content_type: headers["Content-Type"] = content_type return headersdef cu_analyze_binary(endpoint: str, analyzer_id: str, content: bytes, api_version: str) -> str: """ Starts analysis and returns the Operation-Location URL to poll. IMPORTANT FIX: :analyzeBinary expects RAW BYTES (application/octet-stream) in the request body. Do NOT base64-wrap the PDF in JSON. """ url = f"{endpoint.rstrip('/')}/contentunderstanding/analyzers/{analyzer_id}:analyzeBinary" headers = _get_cu_headers(content_type="application/octet-stream") headers["x-ms-client-request-id"] = str(uuid.uuid4()) resp = requests.post( url, params={"api-version": api_version}, headers=headers, data=content, # timeout=180, ) if resp.status_code >= 400: logging.error("CU analyzeBinary failed: %s %s", resp.status_code, resp.text) resp.raise_for_status() op_loc = resp.headers.get("Operation-Location") if not op_loc: raise RuntimeError("Missing Operation-Location header from analyzeBinary response.") return op_locdef cu_poll_result(operation_location: str, timeout_s: int = 240, poll_interval_s: float = 1.0) -> dict: start = time.time() while True: headers = _get_cu_headers() resp = requests.get(operation_location, headers=headers, timeout=60) if resp.status_code >= 400: logging.error("CU poll failed: %s %s", resp.status_code, resp.text) resp.raise_for_status() payload = resp.json() status = (payload.get("status") or "").lower() if status in ("succeeded", "failed", "canceled", "cancelled"): return payload if time.time() - start > timeout_s: raise TimeoutError(f"Timed out waiting for analysis result after {timeout_s}s.") time.sleep(poll_interval_s)# -----------------------------# Function: enqueue_job# -----------------------------@app.function_name(name="enqueue_job")@app.route(route="enqueue-job", methods=["POST"])@app.queue_output( arg_name="msg", queue_name="will-jobs", connection="AzureWebJobsStorage",)def enqueue_job(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse: try: body = req.get_json() except ValueError: return func.HttpResponse( "Invalid JSON body. Expected: {\"blobName\":\"...\", \"docId\":\"...\"}", status_code=400, ) blob_name = body.get("blobName") if not blob_name or not isinstance(blob_name, str): return func.HttpResponse("Missing/invalid 'blobName' (string).", status_code=400) doc_id = body.get("docId") if not doc_id or not isinstance(doc_id, str): doc_id = str(uuid.uuid4()) payload = { "docId": doc_id, "blobName": blob_name, "submittedUtc": datetime.now(timezone.utc).isoformat(), } msg.set(json.dumps(payload)) return func.HttpResponse( json.dumps({"enqueued": True, "job": payload}), mimetype="application/json", status_code=202, )# -----------------------------# Function: process_will# -----------------------------@app.function_name(name="process_will")@app.queue_trigger(arg_name="msg", queue_name="will-jobs", connection="AzureWebJobsStorage")def process_will(msg: func.QueueMessage) -> None: try: raw = msg.get_body().decode("utf-8", errors="replace") logging.info("process_will received raw message: %s", raw) data = json.loads(raw) doc_id = data.get("docId") or str(uuid.uuid4()) blob_name = data.get("blobName") if not blob_name: raise ValueError("Missing blobName in message") # --- Storage config --- conn_str = os.getenv("AzureWebJobsStorage") if not conn_str: raise RuntimeError("AzureWebJobsStorage is not set.") raw_container = os.getenv("RAW_WILLS_CONTAINER", "raw-wills") extracted_container = os.getenv("EXTRACTED_CONTAINER", "extracted-json") curated_container = os.getenv("CURATED_CONTAINER", "curated-json") # --- Download file --- bsc = BlobServiceClient.from_connection_string(conn_str) blob_client = bsc.get_blob_client(container=raw_container, blob=blob_name) logging.info("Downloading blob: container=%s blob=%s docId=%s", raw_container, blob_name, doc_id) content = blob_client.download_blob().readall() logging.info("Downloaded %d bytes for docId=%s blobName=%s", len(content), doc_id, blob_name) # --- CU settings (see note below) --- endpoint = os.getenv("DOCINTEL_ENDPOINT") analyzer_id = os.getenv("DOCINTEL_ANALYZER_ID", "Wills_Analysis") api_version = os.getenv("CU_API_VERSION", "2025-11-01") if not endpoint: raise RuntimeError("Missing DOCINTEL_ENDPOINT in settings.") logging.info("Submitting to CU: analyzerId=%s apiVersion=%s", analyzer_id, api_version) op_loc = cu_analyze_binary(endpoint, analyzer_id, content, api_version) result_payload = cu_poll_result(op_loc) status = (result_payload.get("status") or "").lower() logging.info("Analysis completed with status=%s", status) if status != "succeeded": raise RuntimeError(f"Analysis did not succeed. Status={status}") # --- Write outputs --- extracted_blob_name = f"{doc_id}.json" curated_blob_name = f"{doc_id}.json" bsc.get_blob_client(extracted_container, extracted_blob_name).upload_blob( json.dumps(result_payload, ensure_ascii=False, indent=2), overwrite=True, content_settings=ContentSettings(content_type="application/json"), ) fields = {} contents = (result_payload.get("result") or {}).get("contents") or [] first = contents[0] if contents else {} raw_fields = first.get("fields") or {} fields = {k: extract_field_value(v) for k, v in raw_fields.items()} curated = {"docId": doc_id, "blobName": blob_name, "analyzerId": analyzer_id, "status": status, "fields": fields} bsc.get_blob_client(curated_container, curated_blob_name).upload_blob( json.dumps(curated, ensure_ascii=False, indent=2), overwrite=True, content_settings=ContentSettings(content_type="application/json"), ) extracted_path = f"{extracted_container}/{extracted_blob_name}" curated_path = f"{curated_container}/{curated_blob_name}" upsert_processed_will_from_cu( doc_id=doc_id, blob_name=blob_name, analyzer_id=analyzer_id, result_payload=result_payload, extracted_path=extracted_path, curated_path=curated_path, ) logging.info("Upserted dbo.processed_wills for docId=%s", doc_id) except Exception as e: logging.exception("process_will FAILED: %s", e) raise@app.function_name(name="on_will_uploaded")@app.blob_trigger( arg_name="inblob", path="%RAW_WILLS_CONTAINER%/{name}", connection="AzureWebJobsStorage",)@app.queue_output( arg_name="outmsg", queue_name="will-jobs", connection="AzureWebJobsStorage",)def on_will_uploaded(inblob: func.InputStream, outmsg: func.Out[str]) -> None: full_name = inblob.name or "" container = os.environ.get("RAW_WILLS_CONTAINER", "raw-wills").strip("/") prefix = container + "/" blob_name = full_name[len(prefix):] if full_name.startswith(prefix) else full_name if not blob_name.lower().endswith(".pdf"): logging.info("Skipping non-PDF blob: %s", blob_name) return # Make docId based on the PDF filename (readable) + short unique suffix base = os.path.splitext(os.path.basename(blob_name))[0] # "WILL 2" safe = re.sub(r"[^a-zA-Z0-9_-]+", "_", base).strip("_") # "WILL_2" doc_id = f"{safe}__{uuid.uuid4().hex[:8]}" # "WILL_2__a1b2c3d4" payload = { "blobName": blob_name, "docId": doc_id, "source": "blob-trigger", "submittedUtc": datetime.now(timezone.utc).isoformat(), } outmsg.set(json.dumps(payload)) logging.info("Enqueued will job via binding. docId=%s blobName=%s", doc_id, blob_name)The Final Step: Power BI InsightsOnce my SQL database was filling up with clean data, I connected Power BI.This is where the magic happened. I took all those complex rules (like the age of the Will or missing guardians) and turned them into visual dashboards. I could see trends, risks, and missing information across thousands of documents at a single glance.ConclusionBuilding this wasn’t about using the “coolest” tech; it was about using the right tech. By choosing a deterministic model over a generative one, and building a solid SQL backbone, I created a system that is faster, cheaper, and — most importantly — accurate enough for the legal world.I’ve decided to make this project Open Source. I want to help other engineers who are struggling with “unstructured” data and show that you don’t always need an LLM to build something smart.Check out the GitHub Repository here: GitHubIf you have ideas on how to handle even “messier” documents or want to contribute to the SQL schema, I’d love to hear from you!Why I Skipped LLMs to Extract Data From 100,000 Wills: A System Design Story was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.