Building a Legal Domain-Specific LLM: From Training Optimization to Document Workflow Integration

    This article explores the engineering practices and technical pathways for constructing a legal vertical large language model (LLM). It covers base model selection with lightweight deployment considerations, domain-specific continued pre-training and reinforcement learning from human feedback (RLHF), a rigorous evaluation framework emphasizing task pass rates, and deep integration into real document workflows via intelligent plugins that enable revision and comment-based contract modification. The goal is to help technical teams adapt general LLMs to meet the accuracy, reasoning, and compliance demands of legal practice.

    In the ongoing digital transformation of the legal industry, large language models (LLMs) are increasingly becoming the core technology engine for improving legal workflow efficiency. However, directly applying general-purpose LLMs often introduces pain points such as legal knowledge hallucinations, imprecise logical reasoning, and failure to meet compliance requirements. To truly fit real legal workflows—such as contract review, evidence analysis, and compliance planning—building a dedicated legal vertical LLM has become a technical consensus in the industry. This article analyzes the engineering practice and technical roadmap for legal LLMs from four dimensions: base model selection, training optimization, evaluation systems, and document workflow integration.

    1. Technical Base Model Selection and Lightweight Deployment Considerations

    The first step in building a vertical-domain LLM is choosing an appropriate general-purpose base model. General LLMs possess strong natural language understanding and generation capabilities, which lay the foundation for domain adaptation. When selecting a base model, developers and enterprise users typically face a trade-off between model parameter scale and inference/deployment cost.

    For legal practice scenarios, although the model needs to handle long texts (such as commercial contracts spanning dozens of pages or complex case files), this does not necessarily mean that ultra-large models with hundreds of billions of parameters must be adopted. The current industry trend favors lightweight or medium-sized base models (e.g., in the range of tens of billions of parameters). The advantages of this choice include:

    1. Low inference latency: In interactive scenarios such as contract review, low latency provides a smoother user experience.
    2. Lower deployment cost: Lightweight models are easier to deploy in on-premises environments or to run via more economical cloud API calls, which is crucial for protecting the privacy and security of legal data.
    3. Easier fine-tuning: A smaller parameter count makes domain-specific continued training and reinforcement learning post-training more manageable in terms of compute resources and iteration cycles.

    2. Domain-Specific Continued Training and Reinforcement Learning Post-Training

    Injecting legal knowledge cannot be solved by simple prompt engineering; it requires deep model training. This process typically consists of two core stages: domain-specific continued training and reinforcement learning post-training.

    2.1 Domain-Specific Continued Training

    Domain-specific continued training involves continual pre-training on a large corpus of high-quality legal texts based on a general base model. Such corpora include, but are not limited to: national laws and regulations databases, judicial interpretations, typical guiding cases, standard contract templates, and legal commentary articles.

    During the data preparation phase, strict data cleaning and de-identification are essential. Legal documents often contain sensitive party information. Developers must apply regex matching and named entity recognition (NER) techniques for de-identification to ensure training data compliance. Through continued training, the model can reorganize its internal knowledge representation, making it more accurate when handling legal terminology and statutory citations, significantly reducing the “hallucination” phenomenon.

    2.2 Reinforcement Learning Post-Training (RLHF)

    Legal matters demand high rigor; any ambiguous or incorrect answer can lead to serious legal risks. Therefore, after supervised fine-tuning (SFT), the introduction of reinforcement learning from human feedback (RLHF) or direct preference optimization (DPO) is necessary.

    In this stage, legal domain experts (e.g., senior lawyers, legal directors) participate in building preference datasets. For instance, for the same contract review task, experts score multiple revision suggestions generated by the model. The reward model learns these preferences and guides the main model to favor, in subsequent generation:

    • Using standardized legal language.
    • Accurately identifying core risk points such as breach liability, intellectual property ownership, and dispute resolution mechanisms.
    • Maintaining neutrality and providing reasonable advice when there is no clear legal provision, rather than fabricating content.

    3. Building a Rigorous Model Evaluation Framework

    After model training, strict benchmark testing is required to verify its actual efficacy. The industry typically adopts standardized legal evaluation benchmarks that cover tasks ranging from basic legal knowledge Q&A to complex practical reasoning.

    In terms of evaluation metrics, besides conventional accuracy, the legal domain places particular emphasis on the “full task pass rate.”

    1. Accuracy: Measures the proportion of correct answers on a single task (e.g., “determine whether a clause violates labor law”). A well-performing legal LLM should achieve extremely high accuracy on core review tasks.
    2. Full Task Pass Rate: This reflects the model’s overall stability and end-to-end execution capability. In a real legal workflow, a complete contract review may include multiple sub-tasks such as “missing clause detection,” “risk clause revision,” and “compliance verification.” The model passes the entire task only when it completes all sub-tasks without serious errors. A high full task pass rate indicates that the model has genuine engineering deployment value, rather than merely excelling on a single metric.

    4. Deep Integration into Real Document Workflows

    The ultimate value of an LLM lies in its application. Legal practitioners most frequently use document editors (e.g., Microsoft Word). Therefore, packaging the capabilities of a legal LLM and seamlessly integrating it into document editing tools is a critical step for technical deployment.

    This integration typically takes the form of an intelligent plugin whose core function is to enable “contract modifications based on revisions and comments.” Below is the technical architecture and implementation logic of this integration.

    4.1 Document Parsing and Context Extraction

    When a user triggers the review function in a document editor, the plugin first parses unstructured document content into structured data. This involves document format parsing, paragraph segmentation, and context relationship construction. For long contracts, a sliding window or text summarization technique is used to feed content to the LLM API in batches.

    4.2 LLM Inference and Structured Output

    After receiving the text, the model performs inference based on predefined review criteria (e.g., “check whether the contract includes a confidentiality term”). To ensure that the output can be accurately executed by the document editor, the model’s output format is constrained via a JSON schema.

    An example prompt and output constraint design:

    1. // Expected LLM output structure
    2. {
    3. "issues": [
    4. {
    5. "type": "missing_clause",
    6. "description": "No confidentiality clause found; there is a risk of trade secret leakage.",
    7. "suggested_action": "insert",
    8. "insert_position": "After paragraph 5",
    9. "suggested_text": "Both parties shall keep confidential the trade secrets of the other party learned during the performance of this contract..."
    10. },
    11. {
    12. "type": "risk_clause",
    13. "description": "The liquidated damages ratio is too high and exceeds a reasonable range.",
    14. "suggested_action": "replace",
    15. "target_text": "The breaching party shall pay 50% of the total contract amount as liquidated damages",
    16. "suggested_text": "The breaching party shall pay 10% of the total contract amount as liquidated damages"
    17. }
    18. ]
    19. }

    4.3 Automated Writing of Revisions and Comments

    The plugin client parses the above JSON and calls the underlying APIs of the document editor to convert the model’s suggestions into visual “revisions” and “comments.”

    • For missing_clause (missing clause), the plugin inserts text at the specified location with a comment containing the model’s description.
    • For risk_clause (risk clause), the plugin locates the target_text, enables track changes to replace it with suggested_text, and generates a comment explaining the reason for the modification.

    This architecture of “model inference + document API integration” allows legal professionals to view, accept, or reject the LLM’s modification suggestions directly in their familiar document interface, greatly reducing the learning curve and truly embedding AI capabilities into daily legal workflows.

    5. Conclusion

    Building a legal vertical LLM is a systematic engineering endeavor. It requires not only a strong general-purpose base model but also meticulous domain-specific data training and expert alignment. From improving accuracy on individual tasks to ensuring the full pass rate on complex workflows, and finally to achieving seamless toolchain integration through document plugins, every step demands a deep understanding of the pain points and standards of the legal industry. As LLM technology continues to evolve and the open-source ecosystem flourishes, future legal LLMs will, while safeguarding data privacy, drive even more profound changes in compliance planning, intelligent drafting, and evidence analysis scenarios.