Building, Evaluating, and Deploying Large Language Models for Legal Practice
General-purpose LLMs excel at open-ended Q&A but fall short in legal work, where conclusions must be traceable, processes reviewable, and responsibility attributable. This article walks through the full engineering lifecycle of a legal-domain LLM: decomposing legal work into measurable subtasks, building domain capability through four training stages (domain continued pretraining, instruction fine-tuning, preference alignment, and evaluation-driven iteration), distinguishing task-level pass rate from average accuracy, and connecting structured output to document track-changes and comments via stable anchors and idempotent write-back. It also covers safeguards for high-risk scenarios, a failure-mode troubleshooting checklist, and a three-phase deployment roadmap with clear exit criteria.
1. Why general-purpose LLMs struggle with legal practice
Legal deliverables share three traits: conclusions must be traceable, processes must be reviewable, and responsibility must be attributable. General-purpose LLMs perform smoothly on open-ended Q&A, but when deployed in professional settings they typically fall short in four areas.
- Corpus distribution shift. Legal text has high terminology density, long sentences, and strict referential and cross-reference relationships between clauses. General corpora are naturally sparse on this kind of distribution, so models tend to draw fuzzy boundaries around concepts such as “constitutive elements,” “allocation of the burden of proof,” and “liability caps for breach.”
- Output granularity mismatch. General models lean toward summarizing, whereas practice needs a three-part output—locate the specific clause, explain the nature of the risk, and provide replaceable text—and it must carry its sources.
- Timeliness constraints. Laws, judicial interpretations, and regulatory rules keep changing. Fully baking rule knowledge into the parameters leaves the model unable to react to new laws taking effect or old clauses being repealed.
- Compliance and confidentiality constraints. Client materials, deal structures, and internal review opinions often cannot leave a controlled environment, which directly rules out approaches like handing data to an external API.
Taken together, these four points show that the core engineering problem in the legal domain is not “how large a model to choose,” but how to build domain capability in layers so that every layer is measurable and can be rolled back.
2. Task taxonomy: decomposing “legal intelligence” into measurable subtasks
Talking about “legal LLM capability” in the abstract has no engineering value. You first need a task taxonomy. By output shape, tasks fall into four categories whose failure costs and evaluation methods differ completely.
| Task type | Typical input | Expected output | Cost of failure | Evaluation focus |
|---|---|---|---|---|
| Extraction & structuring | Contracts, judgments, due diligence materials | Field-based JSON | Medium, verifiable downstream | Field-level precision/recall |
| Comparison & consistency checking | Two texts, a checklist vs. the body | List of discrepancies | Medium-high | Recall of discrepancies |
| Risk identification & advice | Contract clauses, fact descriptions | Risk points + revision suggestions + basis | High | Whether key risks are missed, actionability of suggestions |
| Reasoning & planning | Complex facts + multiple constraints | Step-based plan | High | Constraint satisfaction, executability |
There is a counterintuitive engineering conclusion here: the later a task sits in this spectrum, the less suitable it is for a single model to complete end to end. Reasoning and planning tasks should be decomposed into a “retrieve—extract—rule-check—generate-suggestion” pipeline, with the model handling only semantic understanding and text generation, and deterministic judgments delegated to code. The payoff is not only higher accuracy but, more importantly, the ability to localize errors.
Take contract review. It can be split into a four-part pipeline:
Source text -> clause segmentation & numbering -> element extraction (structured) -> rule/knowledge-base comparison -> risk grading -> suggestion generation -> write-back of revisions & comments
Clause segmentation, numbering consistency, and missing-element checks can all be done entirely in code with stable, reproducible results. Only judgments like “is this clause grossly unfair” and “what wording should replace it” require the model.
3. From a general base to a domain model: a four-stage training path
A common approach in the industry is “take an open-source base and fine-tune it on domain corpora,” but what actually sets the ceiling on quality is how well the training data is governed. The stages are described below.
3.1 Stage 1: Domain continued pretraining
The goal is to adapt the model to the distribution of domain text, not to inject factual knowledge. Four practices matter:
- Corpus layering and mixing ratios. Layer the corpus as “high-quality normative text / public judgments / internal annotated data / general text,” and mix in general corpus (usually at a fixed ratio) to avoid catastrophic forgetting.
- Normalized preprocessing. Unify full-width/half-width characters, strip headers and footers, repair broken lines, and preserve clause-numbering hierarchy. Clause numbers are the anchors for later location and citation; they must be structurally preserved during preprocessing and not cleared away as noise.
- Timeliness labeling. Attach effective dates, repeal flags, and jurisdiction tags to each document as sample metadata, and provide timeliness at inference time through retrieval rather than through parameters.
- Redaction up front. Replace sensitive fields such as party names, amounts, and addresses before ingestion. The redaction rules themselves should be managed as configurable policies, not scattered across scripts.
Illustrative code:
# Domain corpus -> continued-pretraining samplesdef build_dcp_samples(docs, cfg):samples = []for doc in docs:text = normalize(doc.raw) # unify whitespace, repair line breaksif not doc.license_ok or doc.jurisdiction not in cfg.allowed_jurisdictions:continuetext = redact(text, cfg.pii_rules) # redaction happens before ingestionfor chunk in pack(text, seq_len=cfg.seq_len):samples.append({"text": chunk,"meta": {"source": doc.id, "effective_from": doc.effective_from,"repealed": doc.repealed, "jurisdiction": doc.jurisdiction},})# mix in general corpus to suppress catastrophic forgettingreturn samples + sample(cfg.general_corpus, ratio=cfg.general_ratio)
3.2 Stage 2: Instruction fine-tuning (SFT)
This stage determines the shape of the output. The core principle is to train on input/output pairs from real tickets rather than relying only on template-synthesized data. Concretely:
- Sample inputs from real work and have domain experts produce reference answers (with clause location, risk grading, revision suggestions, and cited basis).
- Normalize expert answers into a fixed schema, so the model learns not just text but also field structure and how to express confidence.
- Cover long-tail scenarios: malformed formats, OCR noise from scanned documents, missing clauses, mixed jurisdictions—samples that almost never appear in synthetic data.
- Keep negative samples of “should refuse / escalate to a human,” otherwise the model tends to give confident answers to any input.
An example output schema:
{"findings": [{"clause_id": "Clause 7.3 - Liability for Breach","anchor": {"page": 12, "char_start": 3184, "char_end": 3260},"issue_type": "Missing liability cap","risk_level": "high","evidence": [{"type": "statute", "ref": "Civil Code-585", "span": [12, 40]}],"suggestion": "Add an aggregate cap on liquidated damages and tie it to actual losses","needs_human_review": true}],"summary": {"total": 3, "high": 1, "medium": 2, "low": 0}}
The anchor field is a key engineering design: the model only supplies location information, while the actual locating and write-back are done by the host program. This avoids misalignment caused by the model directly manipulating document coordinates.
3.3 Stage 3: Preference alignment
Supervised fine-tuning only teaches “what a correct answer looks like”; it does not teach “which of two correct answers is better.” Preference optimization is used to open up this gap. Common preference dimensions include:
- Whether the suggestion is specific and actionable (offering replaceable text > only pointing out the problem);
- Whether a cited basis is provided (with a source > without);
- Whether risk grading matches the business standard (both over-alerting and missed alerts should be penalized);
- Whether the response expands into unnecessary topics (redundancy penalty).
When building preference data, it is best to collect multiple candidates under the same prompt plus expert rankings, and record the reasoning behind each ranking—that reasoning text is itself good material for later regression tests.
3.4 Stage 4: Evaluation-driven iteration loop
Training is not a one-time action. Feeding human corrections from production back into an evaluation set and new training data forms a loop of “discover failure mode -> attribute it to data/prompt/pipeline -> fix -> regress,” which is more effective than simply increasing model size. In practice, you need a fixed set of immutable regression evaluation sets that are run on every change to prevent local optimizations from causing overall regressions.
4. Evaluation: task-level pass rate vs. accuracy
This is the point most easily misread in the legal domain, because the two metrics measure completely different things:
- Accuracy: computed at fine-grained check points, e.g., “was this clause identified as high risk” or “is the citation correct.” It reflects average capability.
- Task-level pass rate: a complete task contains multiple mandatory checks, and it counts as passed only if all of them pass. It reflects end-to-end usability.
The gap between the two comes from a multiplicative effect. Suppose single-check accuracy is 0.85 and a contract-review task contains 5 independent mandatory checks; then the task-level pass rate is roughly 0.85⁵ ≈ 0.44. In other words, a model with 85% average accuracy may succeed less than half the time at “reviewing a contract in one pass without error.”
This difference has direct implications for engineering decisions:
- The number of mandatory checks must be controlled. Checks that code can complete deterministically (numbering continuity, amount consistency, date format) should not be handed to the model; moving them out of the mandatory set can significantly raise the task-level pass rate.
- Allow staged delivery. Rather than demanding a flawless result in one shot, have the model emit a structured draft, let the system re-validate against rules, and auto-write-back only the high-confidence items.
- Report both metrics. Accuracy alone overstates usability, while task-level pass rate alone cannot tell you which link is dragging things down.
Illustrative scorer:
def evaluate(model, tasks, checks):acc_scores, pass_flags = [], []for t in tasks:out = model(t.input)flags = [ck(out) for ck in checks[t.type]] # each check point judged independentlyacc_scores.append(sum(flags) / len(flags))pass_flags.append(all(flags)) # counts as 1 only if all passreturn {"accuracy": mean(acc_scores),"task_pass_rate": mean(pass_flags),"bottleneck": per_check_failure_rate(...) # locate the weakest link}
You should also track citation verifiability (whether the sources the model gives can actually be retrieved from the knowledge base) and human adoption rate (how many suggestions experts actually accept) separately. These two metrics are closer to business value than accuracy.
5. Integrating with document editor track-changes and comments
The final delivery form of legal intelligence is often not a chat box but revision marks placed directly on the document. This requires model capability to be integrated in a tool-based way into a desktop editor or agent platform, rather than asking users to copy and paste.
5.1 Two integration modes
- Structured write-back (recommended). The model only emits JSON; the host program parses it and calls the document API to generate tracked changes and comments. The advantage is that it is controllable, auditable, and safely reversible on failure.
- Agent autonomous operation. Wrap “read a section,” “add a comment,” “submit a revision,” and “query the basis” as a set of restricted tools, and let the agent decide the call order on its own. It is flexible, but you must limit the writable scope (for example, allow comments only within a selected region, and never allow deletion of original text).
The tool set should follow the principle of least privilege:
TOOLS = ["read_section(doc_id, range)", # read-only"search_knowledge(query, top_k)", # read-only, returns evidence with spans"add_comment(doc_id, anchor, text)", # writes comments only, leaves body text untouched"propose_edit(doc_id, anchor, new_text)" # only generates suggested edits, requires human acceptance]
5.2 Key engineering details
- Anchors must be stable. Do not rely on volatile indices such as paragraph numbers or character offsets. Prefer text-fragment matching plus context fingerprints. Positions drift after the editor inserts content, and stable anchors are a prerequisite for non-overlapping batch write-back.
- Idempotency and deduplication. Running the same document repeatedly should not produce duplicate comments. Use
(clause_id, suggestion_hash)as the idempotency key and skip duplicates. - Graded handling. Generate revision + comment for high-risk items, and only comments for medium/low-risk items, so the document is not drowned in revision marks that make review difficult.
- Reversibility. Log every write operation and support one-click restore to the pre-processing version; keep a read-only snapshot of the original document.
Illustrative write-back logic:
def apply_findings(doc, findings):applied = set()for f in findings["findings"]:key = (f["clause_id"], hash(f["suggestion"]))if key in applied:continue # idempotencyanchor = locate(doc, f["anchor"]) # prefer text anchorif anchor is None:continue # skip on locate failure, defer to humandoc.add_comment(anchor, f["issue_type"] + ": " + f["suggestion"])if f["risk_level"] == "high":doc.propose_edit(anchor, f["suggestion"]) # suggestion only, not auto-appliedapplied.add(key)
6. Safeguards for high-risk scenarios
The cost of errors in legal output is asymmetric: missing a key risk clause costs far more than reporting one extra item. So safeguards at the system level matter more than marginal gains in model capability.
- Mandatory, verifiable citations. Any conclusive output must carry
evidence, and every identifier in theevidencemust be retrievable as source text in the knowledge base; if it cannot be retrieved, the conclusion is judged a hallucination and discarded. - Human review gate. Set different handling strategies by risk level—auto write-back for low risk, comment-pending-confirmation for medium risk, expert sign-off required for high risk. Make “needs a human” an explicit field in the model output rather than guessing it from a threshold.
- Permissions and minimal context. Isolate knowledge-base and document access by project/client, and inject into the model context only content the current user is authorized to access; cross-project retrieval must be enforced as a server-side filter.
- Full-chain audit. Record the input summary, retrieved evidence, model version, output, and human disposition. If a dispute arises, the complete decision chain can be reconstructed.
- Timeliness governance. Return the regulation version as metadata alongside retrieval results, and label the effective status of the basis in the output; any citation to a repealed provision is treated as a failure.
- Prompt and data injection defense. External documents may contain text like “ignore the above instructions,” so when assembling the context you must clearly mark the boundary between data and instructions and strip instructions out of document content.
7. Common failure modes and troubleshooting checklist
| Failure mode | Symptom | Priority investigation direction |
|---|---|---|
| Hallucinated citations | Cites nonexistent clause or case numbers | Whether retrieval actually hit, whether evidence validation is enforced |
| Missed risk | A key clause is not flagged | Whether instruction data covers that risk type, whether a check point is missing |
| Over-alerting | A flood of low-value comments | Whether preference data penalizes redundancy, whether grading rules are too strict |
| Anchor misplacement | A comment lands on the wrong clause | Whether the anchor relies on volatile indices |
| Mid-document quality drop | Sharp quality decline in the middle of long documents | Whether chunking + hierarchical summarization is used, whether a global clause list is preserved |
| Output format drift | JSON parsing fails | Whether schema validation and limited retries are in place, whether failures degrade gracefully |
| Jurisdiction confusion | Rules from different jurisdictions get mixed | Whether the retrieval filter includes jurisdiction tags |
A practical investigation order is: first confirm retrieval hit the correct source text, then confirm the model understood that text, and only then consider tuning the model. A large share of production issues actually originate in retrieval and segmentation, not in model capability.
8. Deployment roadmap
A three-phase rollout is recommended, with a clear exit condition for each phase:
- Phase 1 (verifiable). Do only extraction and comparison tasks, output structured results, and do not touch the body text. Exit condition: field-level precision reaches a business-acceptable threshold, and manual correction cost is below the pure-manual baseline.
- Phase 2 (human-in-the-loop). Connect comment write-back, with experts confirming risk items. Exit condition: human adoption rate hits its target, and high-risk misses are zero.
- Phase 3 (graded automation). Auto-write-back low-risk items with a trace, and establish a continuous regression-evaluation and sample-feedback mechanism.
At the compute and storage layer, this architecture can be carried by a combination of general cloud capabilities: object storage for archiving documents and corpora, a vector retrieval service for the knowledge base, a message queue to decouple asynchronous long-document processing, logging and monitoring/alerting to track adoption and failure rates, and a key management service for credentials and encryption. This keeps model training, inference, and business systems decoupled, so any layer can be replaced and rolled back independently.
9. Summary
The value of a legal-domain LLM does not lie in “answering like an expert” but in output that is locatable, verifiable, and reversible. Toward that goal, the engineering focus lands in four places: first, split domain capability into a layered “retrieve—extract—rule—generate” pipeline so deterministic judgments return to code; second, progressively shape the output through domain continued pretraining, instruction fine-tuning, and preference alignment, while enforcing a structured schema; third, track both accuracy and task-level pass rate so that average metrics do not overstate end-to-end usability; and fourth, make the delivery form a native integration with document revisions and comments, backed by stable anchors, idempotent write-back, permission isolation, and full-chain audit.
When these four pieces are in place, every model iteration can be quantitatively verified and business-side risk stays under control—this is the right way to deploy LLMs in professional settings.
