Building a Legal Domain Large Language Model: Engineering Practices
This article explains how to build a large language model for the legal domain, covering why general-purpose models struggle with legal tasks, how to select a base model and run domain incremental training, a three-layer optimization structure across the base, dialogue, and application layers, a four-dimension evaluation system, typical applications and engineering considerations, and a phased evolution path from incremental training to tool calling. It includes Python examples for corpus cleaning and clause review, with practical guidance on data governance, refusal behavior, traceability, and evaluation design.
1. Why General-Purpose LLMs Fall Short on Legal Tasks
Legal text has three defining characteristics: high terminology density, strong citation relationships, and clear liability boundaries. General conversational models are trained on open-domain corpora, so when they encounter statute citations, validity judgments about clauses, or descriptions of litigation procedures, three types of deviation tend to appear:
- Factual errors, such as treating nonexistent provisions or already-amended rules as valid authority;
- Unprofessional phrasing, where word choices resemble everyday language rather than formal legal expression;
- Systemic confusion, where the applicable relationships between different jurisdictions and between different levels of regulation get mixed up.
The root cause is not parameter count but corpus distribution and optimization objective. A general model’s objective function favors “fluent and useful,” whereas legal scenarios demand “traceable, verifiable, and explicit about refusal.” The core of domain adaptation is therefore to align the model’s knowledge distribution and expression habits with high-quality text in the target domain.
2. Base Model Selection and Domain Incremental Training
Domain models are usually not trained from scratch. Instead, a general conversational base in the ten-billion to hundred-billion parameter range is selected and then incrementally trained on domain data. The reasoning is straightforward: training from scratch is extremely costly and data-hungry, while a base model already has language understanding, long-context modeling, and instruction-following ability, so domain adaptation only needs to close the gap in knowledge and style.
Incremental training data typically falls into four categories:
- Judicial decision documents, which supply reasoning chains of fact → issue → conclusion;
- Laws, regulations, and judicial interpretations, which supply normative phrasing and levels of legal authority;
- Legal knowledge Q&A, which supplies alignment signals in question-answer form;
- Human-annotated data, which supplies high-quality, verifiable supervision signals.
Data governance matters more than data volume. A typical pipeline first normalizes formats and removes duplicates, then masks sensitive information, then applies quality scoring and multiple rounds of cleaning, and finally samples in a stratified way by domain, task, and difficulty. Illustrative cleaning logic:
def build_corpus(raw_docs):docs = [normalize(d) for d in raw_docs] # structural normalizationdocs = [mask_pii(d) for d in docs] # PII maskingdocs = dedup(docs) # near-duplicate removaldocs = [d for d in docs if quality_score(d) > τ] # quality filteringreturn stratified_sample(docs, by=["domain", "task", "difficulty"])
Note that domain data often carries privacy and compliance risk. Masking and access control should be completed before data enters the corpus, not patched during training.
3. A Three-Layer Optimization Structure: Base, Dialogue, Application
Splitting optimization into three layers is an effective way to control complexity and improve maintainability.
The first layer is the base layer, aimed at knowledge injection. Domain incremental training on domain text produces a domain version of the base model that is close to the target industry in terminology, sentence patterns, and normative citation. This layer focuses on perplexity, domain vocabulary coverage, and long-context stability.
The second layer is the dialogue layer, aimed at capability alignment. Supervised fine-tuning on multi-turn domain dialogue data teaches the model to ask follow-up questions, seek clarification, answer by case, and refuse explicitly when evidence is insufficient. The key design here is refusal and uncertainty expression: in legal scenarios, a confidently wrong answer does more harm than no answer.
The third layer is the application layer, aimed at task adaptation. Fine-tuning for tool calling and structured output targets concrete product capabilities, such as retrieving provisions, calling template libraries, and generating structured review opinions. This layer is usually paired with prompt templates and validators:
def review_clause(clause, model, retriever):refs = retriever.search(clause) # retrieve supporting authorityout = model.generate(prompt=build(clause, refs),schema=ReviewReport) # structured outputreturn validate(out, refs) # citation consistency check
The benefit of decoupling the three layers is that a base upgrade does not require redoing all application-layer adaptation, and a new application task does not require retraining the base.
4. Evaluation: From “Does It Sound Right” to “Is It Correct”
A domain model cannot be judged with open-domain preference evaluation. A four-dimension evaluation is recommended:
- Knowledge accuracy: whether statute and rule citations are correct and not already repealed;
- Professional expression: whether terminology and document style are properly formal;
- Task completion: whether contract review covers risk points and whether legal consultation gives an actionable path;
- Safety boundaries: refusal rates for out-of-scope legal opinions, unfounded assertions, and privacy leakage.
The evaluation set should include adversarial samples, such as repealed rules, cross-jurisdiction conflicts, and self-contradictory clauses, to test whether the model “confidently makes things up.” A human review step should also be kept, with review conclusions fed back as new annotation data to close the loop.
5. Typical Applications and Engineering Essentials
Contract review focuses on clause-level risk identification and revision suggestions, and output should be traceable to a location in the original text. Legal consultation focuses on issue summarization and process guidance, and output should separate “settled conclusions” from “items needing further verification.” Document drafting focuses on controllable generation under template constraints.
Engineering also requires attention to long-context segmentation and recall strategy, traceable citation of retrieval results, structured output validation, logging and monitoring alerts, and data-stays-in-domain training for on-premises scenarios. If cloud resources are used, object storage can hold corpora, a container platform can host inference services, and logging and monitoring services can observe quality drift — all standard capability categories.
6. Evolution Path: From Incremental Training to Tool Calling
A pragmatic strategy is to evolve in stages: early on, use domain incremental training to quickly fill knowledge gaps; as the base model’s general capabilities strengthen, shift gradually toward fine-tuning tool-calling ability and retrieval augmentation, externalizing volatile knowledge into an updatable knowledge base; in on-premises scenarios, use small-scale domain data for lightweight training and preference alignment. Model versions keep iterating, but the evaluation set and data governance standards should stay stable — that is the precondition for controllable long-term results.
