Building and Engineering a Legal Domain Large Language Model: From Base Model Selection to Workflow Integration
This article explains why general-purpose large language models fall short in legal scenarios and walks through a four-stage approach to building a legal vertical model: base model selection, domain continued pre-training, post-training alignment, and tool-based deployment. It covers data mixing ratios, preference-data design for cautious outputs, a two-dimensional evaluation framework, a decoupled contract-revision architecture, and common risks with mitigations. Readers will find practical guidance on long-context stability, structured output, citation traceability, and auditable workflows.
1. Why General-Purpose LLMs Fall Short in Legal Scenarios
Legal text has three defining characteristics. First, it is long-document heavy: a single contract can run to tens of thousands of words, with cross-references between clauses. Second, error tolerance is extremely low: a wrong date, amount, or party name can invalidate an entire conclusion. Third, outputs must be traceable: every conclusion has to point back to specific source clauses.
General-purpose models typically underperform on all three points. The reason is not a lack of knowledge but a mismatch between training objectives and task shape. General alignment favors fluent, summarizing answers, whereas legal practice demands structured extraction, clause-by-clause comparison, and verifiable citations.
So the core idea behind a legal vertical model is not to feed the model more statutes. It is to shift the model’s output distribution toward the real shape of legal workflows. The mainstream industry approach can be summarized in four stages: base model selection, domain continued pre-training, post-training alignment, and tool-based deployment.
2. Base Model Selection: Why Lighter Models Are Often Preferred
A common misconception is that vertical tasks require a very large parameter base. In real engineering, a lightweight base is often the better deal, for three reasons:
- Predictable throughput and cost: Contract review is a batch, long-context task, and inference cost grows roughly linearly with context length. Small models have a clear advantage in cost per document.
- Better fine-tuning economics: Domain capability comes mainly from data and training strategy, not from stacking parameters. With the same compute budget, a small base can run more rounds of domain training and alignment experiments.
- Easier private deployment: Law firms and in-house legal teams have strong requirements that data stays within their own environment. A small base is easier to deploy and schedule for concurrency on owned compute.
Selection should focus on three things: long-context stability (recall of information in the middle of long documents), adherence to structured output (JSON or table formats that do not drift), and initial coverage of Chinese legal terminology.
3. Domain Continued Pre-Training: Replacing General Language Sense with Legal Language Sense
The goal of continued pre-training is to adapt the model to the language distribution of domain corpora, not to teach it to answer questions directly. Data mixing is the key. A practical mixing framework:
| Data Type | Suggested Share | Purpose |
|---|---|---|
| Public court judgments and regulatory text | 30%–40% | Build priors for terminology and sentence patterns |
| Structured contract and agreement text | 25%–35% | Strengthen clause segmentation and coreference resolution |
| Legal commentary and academic text | 10%–15% | Improve reasoning and argument coherence |
| High-quality general corpus | 15%–20% | Prevent catastrophic forgetting |
In practice, the general-corpus quota for preventing forgetting must be preserved. Otherwise the model degrades into listing statutes while losing the ability to do common-sense reasoning. Data cleaning should focus on de-identification, normalization of clause numbering, and restoration of table structure.
4. Post-Training Alignment: Calibrating Caution with Reinforcement Learning
What legal scenarios need most is not a “smarter” model but a more cautious one. Post-training usually has two stages: supervised fine-tuning and preference optimization. The key to preference data design is treating overconfidence as a negative sample:
# Preference sample construction (pseudocode)positive = {"conclusion": "Clause 8.2 sets a late-payment penalty of 0.05% per day, with no cap specified","evidence": ["clause_id: 8.2", "page: 7"],"confidence": "medium","need_human_review": true}negative = {"conclusion": "This contract contains no risk clauses", # over-generalized, no citation"evidence": [],"confidence": "high"}
The reward signal should cover three things at once: whether a conclusion is backed by source citations, whether uncertainty is flagged, and whether the model proactively asks for additional materials when information is missing. Engineering also needs a “refuse to answer / escalate to human” path so the model does not force a conclusion when evidence is insufficient.
5. Evaluation: A Two-Dimensional View of Capability
A single accuracy number hides real usability. A two-dimensional evaluation is recommended:
- Task pass rate: A document passes only if all its subtasks (party identification, risk clause location, revision suggestions, format compliance) are correct. This measures end-to-end usability.
- Per-item accuracy: The correct proportion of each extraction and judgment, used to locate capability gaps.
Three specialized test sets should be added: a mid-document recall set for long documents, an adversarial clause set (vague wording, mutually conflicting clauses), and a format adherence set (strict output of revision marks and comment structures). Evaluation should fix random seeds and prompt templates to keep versions comparable.
6. Landing in Real Workflows: Contract Revision as an Example
Model capability creates value only when embedded in a workflow. For document revision, a decoupled architecture is recommended:
Document parsing → clause segmentation and numbering → retrieval augmentation (regulations/template library)→ model generates structured opinions → rule engine validation → write back revisions and comments → human review
Key engineering points: the parsing layer must preserve paragraph hierarchy and numbering, otherwise write-back positions shift; the generation layer outputs a structured intermediate format that a rendering layer converts into document revision marks and comments; the rule engine performs hard validation of amounts, dates, and party names; the full pipeline records citation sources to form an auditable log. The retrieval augmentation layer can use object storage to hold the template library, a message queue to smooth out traffic peaks, and logging plus monitoring and alerting to keep batch tasks observable.
7. Common Risks and How to Avoid Them
- Hallucinated clauses: Enforce “no citation, no conclusion.” Missing citations automatically downgrade the output to pending human confirmation.
- Format drift: Add schema validation to structured output, with automatic retry and graceful degradation on failure.
- Data compliance: De-identify across the training and inference pipeline, keep sensitive data within its own environment, and apply least-privilege access.
- Version drift: Keep a unified version number across the model, prompt templates, and rule library, with a traceable change history.
In summary, the value of a legal vertical model comes from the combination of a suitable base model, high-quality domain data, caution-oriented alignment, and a tool-based workflow, not from parameter scale at a single point. Baidu AI Cloud can provide standardized engineering support for this pipeline through general capabilities such as container platforms, object storage, and monitoring and alerting.
