Building Robust Legal Document Processing Applications with LLMs

anzen · Insurance · 2023 · source Agentic: no · promotional bias: low · source-backed · extracted with prompt 0.5.5 (schema v2)

Generated from extraction.json — do not edit by hand. Every claim cites verbatim source evidence; stated means the quote directly asserts the claim, implied means it supports it indirectly.

Problem

Domain: High-stakes legal and insurance document processing

Anzen needed to use LLMs in document-processing workflows where hallucinated or malformed answers are unacceptable, while source documents have messy layouts, changing inputs, and model behavior can drift over time.

Constraints:

Architecture

Anzen's robust document-processing architecture separates deterministic and generative work. Documents are first cleaned and structured: OCR extracts text, LayoutLM identifies questions versus answers, and the system reconstructs a text representation that preserves the original form's logic. A fine-tuned classifier trained on curated examples decides whether a document is an insurance application before the expensive LLM step. The LLM receives cleaner context and is constrained with structured outputs/function calls. User feedback, saved inputs/outputs, dashboards, latency/performance monitoring, and alerting close the loop so model drift or data changes can be detected and used for future fine-tuning.

Diagram confidence: explicit (topology described by the source).

flowchart LR
  insurance-application-document[Insurance application document] --> ocr-extractor[OCR extractor]
  insurance-application-document --> layoutlm-document-parser[LayoutLM document parser]
  ocr-extractor --> structured-document-representation[Structured document representation]
  layoutlm-document-parser --> structured-document-representation
  structured-document-representation --> document-classifier[Document classifier]
  structured-document-representation --> llm-extraction-step[LLM extraction step]
  document-classifier --> llm-extraction-step
  llm-extraction-step --> function-call-schema[Function call schema]
  llm-extraction-step --> feedback-system[Feedback system]
  llm-extraction-step --> monitoring-system[Monitoring system]
  feedback-system --> monitoring-system
  feedback-system --> fine-tuning-dataset[Fine tuning dataset]
  fine-tuning-dataset --> document-classifier[Document classifier]
Drag to pan · scroll or use +/− to zoom · reconstructed from the source's described component topology

Components

Component Role Interacts with
Insurance application document Complex source document containing tables, checkboxes, questions, answers, and layout-dependent meaning. OCR extractor, LayoutLM document parser
OCR extractor Extracts raw text from scanned or formatted insurance application documents. Insurance application document, Structured document representation
LayoutLM document parser Identifies question and answer regions so the text representation preserves document structure. Insurance application document, Structured document representation
Structured document representation Clean intermediate text representation that reconstructs the form's logical relationships before LLM processing. OCR extractor, LayoutLM document parser, Document classifier, LLM extraction step
Document classifier Fine-tuned smaller model that determines whether a document is an insurance application before routing it onward. Structured document representation, LLM extraction step
LLM extraction step Generative model step used only after preprocessing and classification to answer constrained document questions. Structured document representation, Function call schema, Feedback system, Monitoring system
Function call schema Structured-output contract that makes model responses conform to application-required fields. LLM extraction step
Feedback system First-class product mechanism for users to report incorrect AI results and generate improvement data. LLM extraction step, Monitoring system, Fine tuning dataset
Monitoring system Dashboards, alerting, saved inputs/outputs, latency, and performance tracking for production operation. LLM extraction step, Feedback system
Fine tuning dataset Curated examples and feedback data used to improve classifiers or future models. Document classifier, Feedback system

Data flow

An insurance application enters the pipeline as a layout-heavy document. OCR alone is insufficient, so Anzen combines OCR with LayoutLM to identify questions and answers, reconstructing a cleaner text representation that preserves the form's structure. A fine-tuned classifier first determines whether the document is an insurance application. Only confirmed applications proceed to an LLM step, which receives cleaner context and returns structured data through function-call-style schemas. In production, user feedback, saved model inputs/outputs, dashboards, performance metrics, and alerting monitor whether the system is drifting or misbehaving.

6 supporting quotes
“we process a lot of insurance applications which look something like this and if you just run OCR on this document uh the results you get are actually not very good”transcript, stated
“we first used a model uh called layout LM to identify you know within a particular insurance application which sections are the questions and which are the answers”transcript, stated
“using that as well as the OCR results we were able to reconstruct a much more true to the original Source representation or text representation”transcript, stated
“we instead have first have a classification model that was trained on a few thousand examples um and has really good performance to determine if something is an insurance application”transcript, stated
“and then given it is then we provide it to the llm which gives it a much more constrained problem space and has had much better performance and you know it is important to note that fine-tuning models off like off-the-shelf models you actually don't need as”transcript, stated
“feedback is is great but you should also uh be monitoring things like performance you know you should be saving all the inputs and outputs that you send to your model uh you know ultimately you should have the dashboards necessary to really understand how and if performance is changing”transcript, stated

Why this architecture

The system is built around reducing the LLM's uncertainty rather than assuming the model will stop hallucinating. Function calls constrain output shape; retrieval and multi-step processing limit context to relevant information; LayoutLM/OCR preprocessing improves input quality before the LLM sees the document; a classifier avoids spending generative-model effort on documents that should be rejected; and feedback plus monitoring detect drift from changing providers, changing inputs, or nondeterminism.

5 supporting quotes
“we don't actually need to solve the problem of hallucination in order to build good software on top of these models”transcript, stated
“one of the best ways to fix that is to make sure that you provide the model with the information that it needs to answer your question”transcript, stated
“the cleaner the data that you give to the model is the better job it's going to do in uh actually giving you the right answer”transcript, stated
“really only use generative models when for the things that only generative models can do so you know if for example you want to classify a particular piece of text as you know one or more types of documents or something like that fine-tuning smaller models”transcript, stated
“you always have to assume machine learning models are going to misbehave sometimes uh because you know despite what you think they will”transcript, stated

Models used: ChatGPT / OpenAI models · LayoutLM · Fine-tuned classification model

Scale

Alternatives considered (roads not taken)

Prompt the model not to be wrong

Rejected because: Natural-language instructions still produced fabricated sources, so correctness needs architecture, data, constraints, and monitoring.

“I added custom instructions to chat gbt to tell it to only site sources that it's 100 sure are accurate and and then I asked it to write me an essay about ducks uh and it did a pretty good job uh and it even gave me some sources two of which were real but uh”transcript, stated
“about ducks uh and it did a pretty good job uh and it even gave me some sources two of which were real but uh one of them was not real and uh it's plausible the author exists the author does write about ducks but as far as I can tell this specific paper uh does not exist uh and so in order really”transcript, stated

Specify JSON format through long prompts

Rejected because: Prompt-only formatting is tedious, long, and does not guarantee the exact schema an application needs.

“adding all of these via prompts uh is a little bit tedious and uh well I'll probably end up with a very long prompt”transcript, stated
“at the end of the day I don't really have any confidence that chat gbt will always follow my instructions and give me the exact format I want”transcript, stated

Send the whole document or document set to the LLM for every question

Rejected because: Large contexts can exceed model limits or become expensive; retrieval and multi-step extraction reduce token load.

“the information you want to provide is simply too big to fit in the context that the model uh can accept or in the case when you're using a third-party API often the cost is based on token usage and so if you're sending a really large number of tokens with”transcript, stated
“if you're sending a really large number of tokens with every request it can get expensive very quickly and so there are various different techniques you can use at that point to optimize the the costs and and basically how many tokens you're sending one”transcript, stated

Use naive OCR text as the LLM input

Rejected because: Raw OCR loses relationships among checkboxes, questions, answers, and layout, making the text hard for even humans to reconstruct.

“if you just run OCR on this document uh the results you get are actually not very good um there are you know you can see the yes and no check boxes they're you know under the corporate structure there's uh basically you know when directly translating this to”transcript, stated
“it doesn't quite keep its Integrity in a way that you know someone even a human reading the text would be able to reconstruct what the application said from it”transcript, stated

Use a general LLM for document classification and extraction in one step

Rejected because: A smaller fine-tuned classifier can cheaply decide whether a document belongs in the pipeline, constraining the LLM to confirmed cases.

“rather than giving the model any document and saying you know tell me if this is an insurance application and if it is you know tell me all of this additional information about it”transcript, stated
“we instead have first have a classification model that was trained on a few thousand examples um and has really good performance to determine if something is an insurance application and then given it is then we provide it to the llm which gives it a much”transcript, stated

Patterns

structured-output-contract (validation)

Anzen recommends function calls to define the exact output schema instead of relying on natural-language format instructions.

“now I've actually created a schema of exactly the shape of the data I want for a recipe”transcript, stated
“if I use that as and ask chatgvt to give me a recipe uh and use that uh basically function call as the output it will actually give me exactly the schema I'm looking for so if you're building an application on top of this this is really an excellent way to to get it to really give you the shape of”transcript, stated

rag-retrieval (retrieval)

For large document contexts, the talk recommends embedding passages and queries to retrieve only the most relevant document sections before calling the model.

“embed either the sentences or passages of the PDF and then you uh also embed the query”transcript, stated
“filter down uh the sections of the document that you think are most likely to be relevant and then you only provide those to the model”transcript, stated

prompt-chaining (workflow)

The recommended document workflow extracts structured fields once, then feeds condensed information to a later model step for higher-level judgment.

“the model rather than providing everything you know this is going to be largely dependent on your use case but another approach is to do a multi-step process so for example if you are want to summarize the financial position of a company then let's say you want to ask a bunch of different”transcript, stated
“process each of them once and ask the model to pull out specific Fields you're looking for and then shortly after provide that condensed information”transcript, stated

data-quality-loop (data)

Anzen improves LLM accuracy by investing in OCR/LayoutLM preprocessing and by feeding user feedback into future training and fine-tuning.

“it's worth doing a lot of work to uh you know before you ever give the data data to the model just in order to make sure that it has all the information it needs”transcript, stated
“you can use that for future training and fine-tuning of uh your models or new models which creates sort of a feedback loop”transcript, stated

fine-tuning-adaptation (modeling)

Anzen uses a fine-tuned classifier for document-type detection before generative extraction, reserving LLM work for cases that need it.

“fine-tuning smaller models with a data set you curate is extremely effective”transcript, stated
“we instead have first have a classification model that was trained on a few thousand examples”transcript, stated

observability-tracing (operations)

The production architecture saves inputs and outputs, tracks latency/performance, and uses dashboards and alerting to detect degradation.

“you should be saving all the inputs and outputs that you send to your model”transcript, stated
“you should have the dashboards necessary to really understand how and if performance is changing uh over time”transcript, stated

Tradeoffs

Constrain output with function calls

Chose Schema-defined function-call outputs over Long natural-language JSON formatting prompts.

Rationale: Function calls are more reliable and easier than spelling out every output field in a prompt.

“with function calls um it's this is actually a pretty easy problem to solve”transcript, stated
“it will actually give me exactly the schema I'm looking for so if you're building an application on top of this this is really an excellent way”transcript, stated

Retrieve or condense context before generation

Chose Search and multi-step document processing over Sending all source text for every query.

Rationale: The model needs relevant information, but raw large contexts create context-window and cost problems.

“one of the popular techniques has been search so essentially rather than providing the entire text of the PDF to the model”transcript, stated
“you only provide those to the model rather than providing everything”transcript, stated

Use LayoutLM before LLM processing

Chose Layout-aware preprocessing plus OCR over Plain OCR text.

Rationale: Layout-aware preprocessing preserves the question/answer structure that an LLM needs to reason correctly over insurance forms.

“we first used a model uh called layout LM to identify you know within a particular insurance application which sections are the questions and which are the answers”transcript, stated
“the model did a much better job of um understanding and giving us good uh answers to our questions”transcript, stated

Gate LLM extraction with a classifier

Chose Fine-tuned document classifier first over Letting the LLM both identify and extract every document.

Rationale: A classifier narrows the problem space and lets the LLM operate only on confirmed insurance applications.

“we instead have first have a classification model that was trained on a few thousand examples”transcript, stated
“then given it is then we provide it to the llm which gives it a much more constrained problem space and has had much better performance”transcript, stated

Build first-class feedback and monitoring

Chose Product feedback, dashboards, alerting, and saved inputs/outputs over Relying only on usage metrics or launch-time testing.

Rationale: Explicit correctness feedback is more valuable than rough usage proxies and supports rapid detection plus future model improvement.

“ideally you do have a first class monitor feedback feature of some kind”transcript, stated
“feedback data is actually really valuable and if you implement it properly you can use that for future training and fine-tuning”transcript, stated

Gotchas (what bit them)

Instruction-only anti-hallucination is not enough for high-stakes applications.

Root cause: The model can fabricate plausible sources or answers even when prompted to be certain.

Resolution: Use architecture-level controls: structured outputs, supplied context, preprocessing, monitoring, and feedback.

“I asked it to write me an essay about ducks uh and it did a pretty good job uh and it even gave me some sources two of which were real but uh one of them was not real”transcript, stated
“you need a little bit more than just telling them not to give you wrong information”transcript, stated

Provider model behavior can change after deployment.

Root cause: Third-party models may be updated under the hood, and nondeterministic outputs can vary even for the same input.

Resolution: Build feedback and monitoring loops that detect performance changes quickly.

“the models are changing under the hood which can make mean that you know you might deploy your software and it might be performing well and then it might start suddenly not performing well”transcript, stated
“these models are inherently non-deterministic so if you give it the exact same input twice it generally won't give you the same output”transcript, stated

Raw OCR can destroy the semantics of insurance applications.

Root cause: Checkboxes, tables, questions, and answers encode relationships in layout that plain text loses.

Resolution: Use a layout-aware model plus OCR to reconstruct a structured text representation before LLM processing.

“there are you know you can see the yes and no check boxes they're you know under the corporate structure”transcript, stated
“we first used a model uh called layout LM to identify you know within a particular insurance application which sections are the questions and which are the answers”transcript, stated

Using LLMs for every task increases cost and widens the failure surface.

Root cause: Classification does not require generative capabilities and can be handled by smaller tuned models.

Resolution: Route classification to a fine-tuned model and pass only confirmed cases to the LLM.

“really only use generative models when for the things that only generative models can do”transcript, stated
“then given it is then we provide it to the llm which gives it a much more constrained problem space”transcript, stated

Context stuffing can hit limits or become too expensive.

Root cause: Large document sets may exceed the context window or generate high third-party API token costs.

Resolution: Use retrieval or multi-step extraction to condense relevant information before higher-level reasoning.

“you quickly run into a new problem which is that either you know the information you want to provide is simply too big to fit in the context that the model uh can accept or in the case when you're using a third-party API often the cost is based on token usage and so if you're sending a really large”transcript, stated
“if you're sending a really large number of tokens with every request it can get expensive very quickly”transcript, stated

Evaluation

The talk recommends evaluating production document AI with structured-output validation, classification accuracy, user-reported correctness feedback, saved inputs/outputs for debugging, latency/performance metrics, dashboards, alerts, and trend monitoring over time.

Metrics: Classification accuracy across document types · User-reported incorrect results · Feedback spike alerts · Model input/output logs for debugging · Performance and latency trends · Dashboarded changes over time

4 supporting quotes
“99.9 uh accuracy across for classifying documents across a bunch of different types”transcript, stated
“if I see something that's wrong I can click a button and report that”transcript, stated
“ideally even alerting based on that so that you know if if there's a big spike you can intervene as quickly as possible”transcript, stated
“monitoring your feedback is is great but you should also uh be monitoring things like performance”transcript, stated

Outcomes

The talk frames Anzen's system as production insurance document processing, with a classifier trained on a few thousand examples, reported 99.9% classification accuracy, and monitoring designed for model and data drift over time.

4 supporting quotes
“has really good performance to determine if something is an insurance application”transcript, stated
“99.9 uh accuracy across for classifying documents across a bunch of different types”transcript, stated
“the model did a much better job of um understanding and giving us good uh answers to our questions”transcript, stated
“use this feedback mechanism as a way to continuously improve your product”transcript, stated