Building Legal Domain LLMs: Methods and Practical Guide

    Legal work demands specialized terminology, up-to-date statutes, reliable citations, and multi-step reasoning, which makes general-purpose LLMs risky to deploy directly. This article presents a practical engineering approach for building legal-domain LLMs: selecting a lightweight general base model, injecting legal knowledge through continual pre-training, aligning task behavior with SFT and RLHF/RLAIF, and designing capabilities around real workflows such as contract review, evidence analysis, compliance planning, and document revision. It also covers task-level evaluation, hallucination mitigation with RAG and citation checks, compliance boundaries, and a deployment architecture for enterprise legal applications.

    Building Legal Domain LLMs: Methods and Practical Guide

    Legal text has three major characteristics: highly specialized terminology, strong logical structure, and a high cost of errors. Although general LLMs perform well in open-domain dialogue, they often expose the following problems in legal scenarios. First, the semantic boundaries of legal terms can be ambiguous. Concepts such as “significant misunderstanding” and “obvious unfairness” have strict definitions in judicial contexts, while general models may interpret them according to everyday meaning. Second, legal provisions are highly time-sensitive. Laws and regulations are amended or repealed, and judicial interpretations are updated frequently, so built-in model knowledge can quickly become outdated. Third, hallucination is extremely costly in legal scenarios. Fabricating a non-existent case or statute may directly mislead decision-making. Fourth, legal reasoning requires multi-step argument chains. For example, analyzing the validity of a contract clause often requires considering the capacity of the parties, the authenticity of intent, the legality of content, and formal compliance at the same time, which places high demands on the model’s long-chain reasoning ability.

    Therefore, the industry generally agrees that the reasonable path for building a legal-domain model is not to train from scratch, but to perform domain adaptation on a general base model with strong reasoning ability. This approach is consistent with the methodology for building models in other high-barrier vertical domains such as healthcare and finance.

    2. Technical Route: Base Model Selection, Mid-Training, and Post-Training

    2.1 Trade-offs in Base Model Selection

    A common choice in practice is to use a lightweight general model with a moderate number of parameters as the base. The reasons are as follows: legal tasks are mostly text understanding and generation, and are sensitive to compute cost; lightweight models are easier to deploy privately, satisfying the compliance requirements of law firms and corporate legal departments that data must not leave the intranet; and lightweight models have low inference latency, making them suitable for embedding into interactive toolchains such as document editing and contract comparison. When selecting a base model, priority should be given to evaluating long-context capability (contracts can easily run to tens of thousands of characters), instruction-following ability, and performance on logical reasoning benchmarks.

    Mid-training is the first step in domain adaptation: after general pre-training and before instruction fine-tuning, the model is continually pre-trained on a large-scale legal corpus. The corpus usually includes:

    • Laws and regulations library: currently effective laws, administrative regulations, departmental rules, and local regulations, with a version and validity annotation system;
    • Judicial documents: desensitized judgments and rulings, with emphasis on retaining the court’s reasoning section, which is the core material for training legal reasoning ability;
    • Contract templates and clause libraries: covering major types such as sales, leasing, labor, and equity;
    • Legal theory and practice literature: textbooks, commentaries, and lawyer practice articles.

    The key to mid-training is corpus mixing ratio. If the proportion of legal corpus is too high, general capabilities may degrade (catastrophic forgetting). In engineering practice, a common approach is to mix general corpus with domain corpus through replay, and determine the ratio through small-scale controlled experiments. Training usually uses a lower learning rate to avoid damaging the base model’s existing language capabilities.

    2.3 Instruction Fine-Tuning and Reinforcement Learning Post-Training

    The model obtained from mid-training has legal knowledge reserves, but it does not yet “work like a lawyer.” Supervised fine-tuning (SFT) is needed to teach the model task paradigms. Typical tasks include:

    Task type Example instruction
    Contract review Identify clauses in the following procurement contract that are unfavorable to Party B, and explain the legal basis
    Evidence analysis Based on the case description, determine whether this set of evidence can form a complete evidence chain
    Compliance planning Outline the data export compliance points for an enterprise conducting cross-border e-commerce business
    Legal consultation An employee is unilaterally reassigned and demoted; what rights can the employee assert?

    After SFT, reinforcement learning post-training methods such as RLHF/RLAIF are introduced to further align the model with professional preferences. Reward signal design in legal scenarios has its own particularities: in addition to general helpfulness and harmlessness dimensions, constraints such as “cited statutes actually exist,” “legal conclusions are consistent with the cited basis,” and “when uncertain, explicitly state uncertainty rather than forcing an answer” should be added. Such programmatically verifiable reward items are especially effective in suppressing legal hallucination.

    A deployable legal model should design its capabilities around workflows rather than single-point question answering.

    Contract review is the most mature direction. The model needs to complete four steps: clause extraction, risk point identification, missing clause prompts, and revision suggestions. In engineering practice, long contracts are usually processed in chunks: first perform clause-level classification, then conduct fine-grained analysis of high-risk clauses such as breach liability, jurisdiction agreements, and intellectual property ownership.

    Evidence analysis requires the model to understand the three properties of evidence (authenticity, legality, and relevance) and the standard of proof. It should be able to help map evidence to the facts to be proven and identify weak links in the evidence chain.

    Compliance planning is a more generative task. The model needs to combine an enterprise’s business description and output a phased, department-specific compliance remediation checklist, rather than generically listing regulations.

    Document drafting and annotated revision are interactive scenarios. Unlike one-shot generation, these scenarios require the model to work in “track changes” mode—that is, to output traceable change marks and explanations of modification reasons rather than directly overwriting the original text, so that lawyers can review and confirm. This requires the model to output structured difference descriptions, for example, expressing each modification as a four-tuple of location + original text + suggested text + reason, which the upper-layer application renders as tracked changes and comments in document software.

    1. {
    2. "suggestion": {
    3. "anchor": "Article 8, paragraph 2",
    4. "original": "Party A has the right to terminate this contract at any time",
    5. "revised": "Party A has the right to terminate this contract after providing 30 days' written notice",
    6. "reason": "An unconditional termination right without a notice period risks being deemed an invalid standard clause",
    7. "risk_level": "high"
    8. }
    9. }

    Evaluation of legal models should cover three levels:

    1. Legal knowledge benchmarks: multiple-choice and true/false questions in the style of legal professional qualification examinations, testing statute memory and basic understanding. Several public legal capability evaluation sets are already available in the industry for reference.
    2. Task-level evaluation: using end-to-end task completion quality as the metric, such as risk point recall and false positive rate in contract review, and factual accuracy of statute citations. More valuable than single-question scores is the “task full pass rate”—the proportion of complete tasks in which all sub-steps are correct. This can more realistically reflect the model’s usability in practice.
    3. Human review evaluation: practicing lawyers conduct blind reviews of outputs, focusing on reasoning quality and operability.

    Engineering practice should also establish red-team test sets specifically covering error-prone situations: repealed regulations, distinctions between similar concepts (such as “earnest money” versus “advance payment”), and cross-jurisdiction conflicts.

    5. Hallucination Governance and Compliance Red Lines

    Hallucination governance in legal scenarios requires a multi-pronged approach. Retrieval-augmented generation (RAG) is infrastructure: when a model answer involves specific statutes or cases, it must be generated based on retrieved authoritative text and include sources. On the output side, citation consistency checks should be added, using programs to compare statute numbers in generated content with the retrieval library. For questions outside the model’s knowledge boundary, the model should be trained to explicitly express uncertainty.

    At the same time, product positioning must be clear: such tools are assistants to lawyers, not replacements. Outputs should always indicate that they “do not constitute legal advice.” Especially in scenarios aimed at non-professional users, disclaimers and human review processes are indispensable. At the data level, case materials involved in training and inference must be desensitized, and private deployment solutions should support full-link data staying within the domain.

    A typical enterprise-grade legal intelligence application architecture includes: the underlying model service (inference engine + vector retrieval + legal knowledge base), the middle task orchestration layer (contract parsing, clause segmentation, and multi-round review state management), and upper-layer application integration (document editing plugins and case management system integration). For cloud deployment, a general container platform can be used to host inference services, object storage can manage documents and corpora, and logging and monitoring alerts can help ensure service stability. For data-sensitive customers, localized deployment can be adopted, running a lightweight model plus knowledge base under limited compute.

    Conclusion

    The competitiveness of legal-domain LLMs does not depend on parameter scale, but on domain data quality, post-training alignment strategies, and fit with real workflows. Starting from a lightweight base, injecting domain knowledge through mid-training, aligning professional preferences with reinforcement learning, and connecting to document toolchains through structured output is an engineering paradigm that has been widely validated as feasible. As evaluation systems improve, practice-oriented metrics such as “task full pass rate” will push these models from “being able to answer questions” toward “being able to do work.”