Building Legal Domain LLMs: Technical Construction and Engineering Practices

    This article examines how to build and deploy domain-specific large language models for legal work. It covers the full path from selecting an efficient base model and running domain mid-training to reinforcement-learning alignment, task-level evaluation, and integration into real workflows such as contract review, evidence analysis, and compliance planning. The discussion highlights practical engineering considerations including data mixing and decontamination, preservation of legal document structure, long-context training, expert preference data, citation correctness, hallucination control, and cloud-native deployment. The overall positioning is assistive rather than replacement: legal LLMs should support professional judgment inside existing legal workflows.

    Building Legal Domain LLMs: Technical Construction and Engineering Practices

    In recent years, general-purpose large language models have shown strong capabilities in text generation, knowledge question answering, and similar tasks. However, when they are applied directly to legal practice, a series of problems quickly emerges. Legal text has a highly specialized expression system: the same word can mean very different things in the context of a statute and in everyday language; contract clauses are bound by strict logical constraints; and the formatting standards for judicial documents are extremely rigorous. More importantly, legal work has very low tolerance for error. A single misinterpreted clause or an incorrect citation of a legal provision can cause real losses for a client.

    As a result, the industry has gradually reached a consensus: a model for legal scenarios cannot simply be a general model with prompt templates attached. It requires a systematic vertical-domain training path. Using common industry technical approaches as a reference, this article breaks down the complete methodology for a legal-specific large model, from base model selection to engineering deployment.

    1. Base Model Selection: Balancing Lightweight Design and Efficiency

    The first major technical decision for a legal domain model is base model selection. In practice, a common approach is to choose a lightweight base model with a moderate parameter count and fast inference speed, rather than immediately stacking an extremely large parameter model. There are three main reasons:

    1. Trade-off in domain density: The difficulty of legal tasks lies more in domain knowledge and rule constraints than in the breadth of general knowledge. A medium-sized model with sufficient domain training often performs more reliably than a large model that has not been adapted to the domain.
    2. Controllable deployment cost: Law firms and corporate legal teams have a strong need for private deployment. A lightweight base model can complete inference and even fine-tuning under limited compute conditions, lowering the barrier to deployment.
    3. Latency-sensitive scenarios: Contract review often requires scanning hundreds of pages of documents clause by clause. Inference throughput and first-token latency directly affect the practical usability of the tool.

    After selecting the base model, technical teams typically preserve its general dialogue and reasoning capabilities, then inject legal expertise through subsequent training. This helps avoid catastrophic forgetting, where the model “learns law but forgets language.”

    2. Mid-Training: Reshaping the Model’s Knowledge Structure with Domain Corpora

    Mid-training is a core stage for a legal-specific model. It inserts a large-scale period of domain continued pretraining between pretraining and instruction fine-tuning. Data sources typically include:

    • Laws, regulations, and judicial interpretations: structured and highly authoritative, and a primary source of rule knowledge;
    • Judicial judgments and court documents: massive in volume, containing the complete chain of fact finding, legal application, and reasoning;
    • Contract templates and practice documents: covering language patterns for drafting and review scenarios;
    • Law textbooks and academic literature: providing conceptual systems and theoretical frameworks.

    In engineering implementation, several points deserve attention:

    Data mixing and decontamination. Legal corpora and general corpora need a reasonable mixing ratio; in practice, ratios between 1:1 and 1:3 are common. At the same time, strict deduplication and decontamination must be performed on evaluation sets. Otherwise, evaluation scores become meaningless.

    Preservation of structural information. The structure of legal documents carries semantics: clause numbering, reference relationships, and revision marks are all important training signals. It is advisable to preserve these structural markers during the cleaning stage rather than flattening everything into plain text.

    Tokenization and long context. Contracts and case files can easily reach tens of thousands of tokens. During training, the context window needs to be extended accordingly, and long-document samples should be used so the model can learn cross-paragraph factual associations.

    3. Reinforcement Learning Post-Training: Aligning with Legal Experts’ Judgment Standards

    If mid-training addresses “knowing law,” reinforcement learning post-training—RLHF/RLAIF-style methods—addresses “thinking like a lawyer.” Alignment in legal scenarios has its own characteristics:

    • Strong correctness constraints: Reward models need to identify incorrect citations of legal provisions, logical leaps, and mismatches between conclusions and supporting evidence, not just language fluency.
    • Standardized risk expression: A good legal opinion should mark uncertainty and distinguish facts from inferences. This kind of “prudent expression” can be modeled explicitly through preference data.
    • Clear refusal boundaries: For specific legal advice that requires a professional license to provide, the model should learn to give an informative response and recommend consulting a professional.

    One feasible implementation process is: first build preference-pair data annotated by senior legal practitioners and train a reward model; then use a policy optimization algorithm to iterate the model’s outputs. It is important to note that legal annotation is extremely costly. An “AI-assisted first-pass labeling plus expert review” approach can be used to control costs, while multi-annotator consistency checks ensure data quality.

    Evaluation of legal models cannot rely only on general benchmarks; it must be designed for real tasks. Common industry evaluation dimensions broadly include:

    1. Task-level pass rate: Using a complete task as the unit—for example, “complete a risk review of a contract and output revision suggestions”—and calculating the proportion of all sub-items that pass. This metric is closer to the real user experience than single-point accuracy, and it better exposes the model’s weaknesses on long-chain tasks.
    2. Classification and extraction accuracy: For tasks such as determining applicable legal provisions, extracting party information, and identifying disputed issues, accuracy, F1, and similar metrics can be used for quantification.
    3. Citation correctness: The authenticity and relevance of citations to legal provisions and cases in generated content.
    4. Robustness and hallucination rate: The ability to resist nonexistent legal provisions and fabricated cases.

    As an example of common practice in public evaluation, a combination such as “a full-task pass rate of about 19% and an overall accuracy of about 86%” precisely shows that individual capabilities can be relatively strong, but end-to-end completion of complex legal tasks remains a shared technical challenge across the industry. When building evaluation sets, they should cover different jurisdictions and different business types, and should be updated dynamically to prevent benchmark gaming.

    5. Engineering Deployment: From Model Capabilities to Real Workflows

    Model training is only the starting point. The real value lies in embedding the model into legal workflows. The deployment priorities for three typical scenarios are as follows:

    Contract review. The core is to embed model capabilities into the document editing environment. After identifying risky clauses, the model presents suggested changes in the form of tracked changes plus comments, rather than directly rewriting the original text, so that lawyers retain final decision-making authority. Technically, multiple modules need to work together: document structure parsing that preserves formatting and revision marks, clause segmentation, risk classification, and revision suggestion generation. Model outputs need to be written back to the document through a structured intermediate representation, such as a JSON description of the position plus the suggested content.

    Evidence analysis. When facing massive case files, a combined approach of retrieval augmentation plus long-context reasoning can be used: first perform structured extraction and indexing of evidence materials, then have the model complete reasoning tasks such as timeline construction and detection of contradictions in the evidence chain.

    Compliance planning. This requires combining a regulatory library with model reasoning. The model interprets the business scenario, matches applicable clauses, and generates a compliance checklist. Regulatory updates are handled through hot updates to the knowledge base, avoiding frequent model retraining.

    At the deployment level, object storage can be used to manage document materials, message queues can decouple long-task processing, container platforms can provide elastic inference scaling, and logging, monitoring, and alerting services can help ensure service stability. These are all capabilities that can be assembled from common cloud-native components.

    Conclusion

    The technical path for legal-specific large models can be summarized as follows: a lightweight base model as the foundation, domain corpus mid-training to inject knowledge, reinforcement learning to align with expert judgment, task-level evaluation to guide iteration, and finally integration into real workflows such as contract review, evidence analysis, and compliance planning in an “assist rather than replace” posture. As evaluation systems mature and toolchains improve, vertical domain models will become an important paradigm for deploying large models in deep, high-stakes environments. Their methodology also offers useful lessons for other high-barrier professional fields such as healthcare and finance.