Practical Guide to Building Domain-Specific Large Models for Legal Use Cases
This article explains why general-purpose large models struggle with real legal work and how to build a legal-domain model around actual workflows. It covers a two-stage training approach combining domain-adaptive pretraining and post-training, a two-dimensional evaluation system, integration patterns for contract review, evidence analysis, and compliance planning, plus hallucination controls and observability. The goal is structured, traceable output that legal teams can verify rather than fluent conversation.
1. Why General-Purpose LLMs Fall Short in Legal Practice
Legal text has three defining characteristics: high terminology density, a large share of long documents, and conclusions that require traceable reasoning chains. General foundation models perform well in open-domain conversation, but when handed a merger agreement that runs dozens of pages, problems cluster in three areas:
- Weak semantic distinction between clauses. Terms such as “shall” and “may,” or “damages” and “compensation,” get treated as interchangeable.
- Broken cross-references. Terminology defined in a definitions clause is not carried back into the obligation clauses that rely on it.
- No localization in the output. Opinions cannot be traced back to a specific paragraph, so legal staff are unwilling to act on them directly.
The core objective of a legal-domain model is therefore not better conversation. It is embedding model capability into a real workflow: the input is documents and case files, and the output is structured opinion with location information.
2. A Two-Stage Training Paradigm: Intermediate Training and Post-Training
2.1 Domain-Adaptive Pretraining
Intermediate training addresses the language distribution problem. The approach is to continue self-supervised training on a lightweight base model, using a corpus drawn mainly from public court judgments, statutes and regulations, standard contract templates, and academic literature. The emphasis is on cleaning and deduplication: removing passages that contain personal sensitive information, normalizing statutory citation formats, and restoring document layout before ingesting scanned files. This stage typically requires no human annotation, keeps cost manageable, and yields a marked drop in perplexity on legal sentence patterns.
A simplified example of how training data is organized:
# Domain intermediate training sample: plain text, truncation and packing onlydef build_domain_batch(texts, tokenizer, max_len=4096):buf, ids = [], []for t in texts:ids.extend(tokenizer(t)["input_ids"])while len(ids) >= max_len:buf.append(ids[:max_len])ids = ids[max_len:]return [{"input_ids": b, "labels": b} for b in buf]
2.2 Post-Training: Supervised Fine-Tuning Plus Reinforcement Learning
Post-training addresses task alignment. In the supervised fine-tuning stage, instruction data is constructed where each sample contains a task type, an input document, and a reference output. Outputs use a unified structured format so they can be parsed downstream. The reinforcement learning stage introduces preference pairs (an “acceptable opinion” and an “unacceptable opinion” for the same question), with the reward signal typically composed of three parts: whether the conclusion is correct, whether the citation is verifiable, and whether the format is compliant.
{"task": "contract_review","clause_id": "Section 7.2","risk_level": "high","issue": "No cap specified for the liquidated damages ratio","evidence": {"page": 6, "span": [412, 468]},"suggestion": "Add a cap on cumulative liquidated damages as a ratio of the total contract price"}
The critical field is evidence. A legal opinion without location information is practically unusable in engineering terms.
3. Evaluation: Why Two Dimensions Matter
A single accuracy figure hides real usability. The common industry practice is to report two families of metrics side by side:
- Task pass-all rate: every sub-item in a single output must be correct, and any single error fails the whole case. This metric is strict, but it matches the actual experience of legal teams: ten risk points in one contract, and missing one can cause real loss.
- Overall accuracy: the proportion of correct results counted by field or by sub-item, reflecting average capability.
The 19.2% pass-all rate and 86.23% accuracy mentioned in the source material illustrate exactly this gap between the two dimensions: average performance is already substantial, while zero-defect delivery still has clear room for improvement. The engineering response is not to wait for a perfect model but to design a human-in-the-loop process: the model handles full-volume initial screening and localization, and humans review only high-risk and low-confidence segments.
4. Integrating into Real Workflows
4.1 Contract Review
A four-step pipeline is recommended: parse, split, review, and write back. Document parsing preserves paragraph numbering and coordinates. Splitting follows clause boundaries rather than a fixed length, avoiding semantic fragmentation. The review stage calls the model in batches. In the write-back stage, structured results are written into the document as tracked changes and comments, so legal staff can confirm or reject them in the editor they already use.
4.2 Evidence Analysis
Evidence work emphasizes timelines and contradiction detection. Materials can first be extracted into a unified entity structure and then handed to the model for consistency judgment:
entity: payment obligationsource: Exhibit A page 3 / Exhibit B page 11conflict: amount mismatch (1.2M vs 1.02M)confidence: 0.78
4.3 Compliance Planning
Compliance tasks are mostly rule mapping: mapping external regulatory requirements onto internal policy clauses and producing a gap list with remediation priorities. Here the rule base should sit outside the model and be injected through retrieval augmentation, so rule versions remain manageable and rollback-safe.
5. Hallucination Control and Observability
Legal scenarios demand zero tolerance for hallucination. Four layers of protection are recommended:
- Retrieval augmentation, so every conclusion carries a statutory source.
- Citation verification, where a program compares the cited text against the original and discards the conclusion on any mismatch.
- Confidence-threshold routing, sending low-confidence samples to human review.
- Full-chain logging that records the input version, model version, and prompt template version to support incident review.
These capabilities can be built on general-purpose cloud primitives such as object storage, message queues, logging services, and monitoring and alerting, without binding to any specific vendor interface.
6. Deployment Recommendations
Start from a narrow scenario, such as review of a single contract type, and first establish annotation guidelines and an evaluation set before expanding the task surface. Treat the model as a high-speed initial screener rather than the final decision maker, and continuously feed rejected online samples back into preference data accumulation. In comparable scenarios, Baidu AI Cloud typically advises customers to build an evaluation baseline first and only then discuss scaling, an order that effectively avoids an imbalance between investment and return.
