A Practical Guide to Building a Legal LLM: From Base Model Selection to Contract Review

    As the legal industry moves from digitization to intelligent automation, general-purpose large language models often struggle with long contracts, complex case facts, and compliance judgments, producing factual errors ("hallucinations") and lacking domain depth. This guide walks through six stages of building a legal-specific LLM: base model selection, domain-adaptive intermediate training, post-training with preference optimization, contract review application, engineering integration, and evaluation—with a pre-launch security checklist included at the end.

    Building a Legal LLM: From Base Model Selection to Contract Review

    As artificial intelligence continues to advance, the legal industry is moving from digitization toward intelligence. Legal work is data-intensive, logically rigorous, and unforgiving of errors. When general-purpose large language models handle long contracts, complex case details, and compliance judgments, they frequently produce factual errors (known as “hallucinations”) and lack sufficient professional depth. Training a specialized model for legal workflows is therefore a viable path to combining AI with legal practice.

    This guide breaks the build process into six stages: base model selection, domain-adaptive intermediate training, post-training with reinforcement learning, contract review application, engineering integration, and effect evaluation. A pre-launch security checklist is included at the end.

    1. Selecting a Lightweight Base Model

    A common industry practice is to start with an open-source base model of moderate parameter size and then adapt it to the legal domain. This is not the only approach, but it is fairly common in private deployment scenarios. When comparing candidates, evaluate the following dimensions:

    • Parameter size: Models in the 7B–14B range can run inference on a single mid-to-high-end GPU, making them suitable for on-premise deployment at law firms and in-house legal teams. Larger models generally have stronger comprehension but higher memory and latency costs.
    • Context length: Contracts and case files often exceed tens of thousands of words. Confirm the model’s native context length and test clause recall on real long documents.
    • License: Check the commercial terms, redistribution terms, and any usage restrictions on fine-tuned derivatives.
    • Compute and latency: Estimate inference throughput and time-to-first-token based on your expected concurrency. If reviewing one contract takes several minutes, users will likely find it unacceptable.
    • Chinese-language capability: Legal texts contain many Chinese terms and fixed phrasings, so benchmark the base model’s starting performance on Chinese legal questions.

    We recommend consolidating these metrics into a base model evaluation sheet with fields such as: long-contract clause recall, time-to-first-token, single-GPU memory usage, license restrictions, and baseline score on Chinese legal questions. Selection decisions should be based on your own evaluation set—not just public leaderboard scores.

    2. Domain-Adaptive Intermediate Training

    The goal of intermediate training is to familiarize a general model with legal terminology, document structures, and the expression patterns of legal reasoning. The corpus typically includes current laws and regulations along with their revision histories, public court decisions, contract templates and model texts, and legal commentaries and textbooks.

    Corpus processing involves three steps:

    Step 1: De-identification. Remove personal information such as party names, ID numbers, addresses, and bank account numbers, and sample-audit to verify the de-identification was thorough.

    Step 2: Cleaning and deduplication. Remove malformed formatting, duplicate passages, and low-quality web content to prevent the model from memorizing large blocks of repeated text.

    Step 3: Mix ratio design. If the legal corpus share is too high, the model’s general writing and conversational abilities may degrade. A common practice is to mix in a proportion of general-purpose corpus as replay data to reduce the risk of catastrophic forgetting. The exact ratio should be determined through ablation experiments rather than copying a fixed value. The table below is a reusable ablation experiment template:

    Experiment ID Legal corpus share General replay share Legal task score General task score Catastrophic forgetting observations
    A1 TBD TBD
    A2 TBD TBD
    A3 TBD TBD

    After training, evaluate on both legal and general tasks and observe how each capability changes. If general task scores drop noticeably, increase the replay ratio and retrain.

    3. Comparing Post-Training and Retrieval Approaches

    Supervised fine-tuning (SFT) teaches the model to answer in the format demonstrated by examples. However, legal judgments involve weighing rights and obligations, and examples alone often fail to cover edge cases—which is why preference optimization is commonly added after SFT.

    The table below compares three post-training techniques:

    Technique Data format Best suited for Main cost
    SFT Input–ground-truth answer pairs Fixed-format outputs, basic Q&A Human effort to label ground-truth answers
    RLHF Reward model + reinforcement learning Tasks requiring fine-grained preference ranking Reward model training and tuning are complex
    DPO Chosen/rejected answer pairs for the same question Aligning with expert preferences; simpler workflow Pairwise preference data labeling

    RLHF may have a higher performance ceiling, but its engineering complexity is also greater. Small teams usually start with SFT plus DPO. DPO preference data requires clear labeling guidelines, including criteria for choosing versus rejecting answers, annotator qualification requirements, an arbitration process for disagreements, and metrics for measuring inter-annotator consistency.

    Retrieval-augmented generation (RAG) is not a post-training technique. It does not update model parameters; instead, it retrieves documents from an external knowledge base at inference time and feeds them to the model as context. RAG suits scenarios that depend on the latest regulations and require traceable citations. Its main costs lie in knowledge base maintenance and retrieval quality tuning, so we cover it in the contract review workflow in the next section.

    4. Putting Contract Review into Practice

    Contract review is one of the most frequent and time-consuming tasks in legal practice. The model must handle long contexts and understand content at the clause level. A common architecture combines RAG with a fine-tuned model: the fine-tuned model handles clause comprehension and generates structured opinions, while RAG supplies standard templates, a risk clause library, and regulatory references. The full workflow consists of six steps:

    1. Clause segmentation: Split the contract by numbered headings; for overly long clauses, split by sentence while preserving clause numbers and section context to avoid cutting off meaning.
    2. Retrieval: Build separate indexes for the standard template library, risk clause library, and regulation library, and use hybrid retrieval—combining keyword and vector search—to recall candidate materials.
    3. Comparison: Align each clause under review with the corresponding standard template clause and list substantive differences, such as penalty ratios, liability caps, and jurisdiction provisions.
    4. Generate structured opinions: The model outputs review results in fixed fields; example fields are shown in the next section.
    5. Citation traceability: Every opinion must include its source location in the original text and the knowledge base document ID. Opinions that cannot be linked back to the source or knowledge base should be flagged as unusable and never shown to users.
    6. Human review: High-risk opinions or those below a confidence threshold must be confirmed by a lawyer before entering the final report.

    5. Engineering Integration: API Skeleton and Structured Output

    The following code shows the basic skeleton for calling the review service. The endpoint and key are read from environment variables and never hardcoded. A permission check runs before the call, and failures retry with exponential backoff.

    1. import os
    2. import time
    3. import requests
    4. API_URL = os.environ["LEGAL_LLM_ENDPOINT"]
    5. API_KEY = os.environ["LEGAL_LLM_KEY"]
    6. ALLOWED_ROLES = {"lawyer", "legal_reviewer"}
    7. def review_contract(clauses, tenant_id, user_role, retries=3, timeout=60):
    8. if user_role not in ALLOWED_ROLES:
    9. raise PermissionError("Current role is not authorized to start contract review")
    10. payload = {
    11. "task": "contract_review",
    12. "tenant_id": tenant_id,
    13. "clauses": clauses,
    14. "response_format": "json",
    15. "temperature": 0.1,
    16. }
    17. headers = {"Authorization": f"Bearer {API_KEY}"}
    18. for attempt in range(retries):
    19. try:
    20. resp = requests.post(API_URL, json=payload, headers=headers, timeout=timeout)
    21. resp.raise_for_status()
    22. return resp.json()
    23. except requests.RequestException:
    24. if attempt == retries - 1:
    25. raise
    26. time.sleep(2 ** attempt)

    The model’s review opinions should be returned as JSON with a fixed structure, making them easy to store, display, and audit. Here is an example of a single opinion:

    1. {
    2. "contract_id": "C-2026-0001",
    3. "clause_id": "7.2",
    4. "risk_level": "high",
    5. "clause_location": {"page": 5, "paragraph": 2},
    6. "issue": "Penalty ratio is significantly higher than the standard template provision",
    7. "legal_basis": ["Civil Code Article 585"],
    8. "suggestion": "Adjust the penalty ratio to match the standard template and add language allowing it to be contested if excessive",
    9. "citations": [{"doc_id": "T-034", "source": "Standard template, Clause 4"}],
    10. "confidence": 0.72,
    11. "needs_human_review": true
    12. }

    Field explanations: risk_level is used for sorting and assignment. clause_location pinpoints the clause in the original text. Statutes in legal_basis must be verifiable in the regulation library—the model should never fabricate statute numbers. citations provides the traceability basis. confidence is the model’s confidence estimate; it is not the same as the accuracy of the legal conclusion, and the threshold should be set based on evaluation results. When needs_human_review is true, the interface should require lawyer confirmation.

    6. Evaluating Effectiveness

    The goal of evaluation is to answer one question: does the model actually help lawyers review real contracts faster and more accurately?

    First, build a test set. The test set must be fully isolated from training data and stratified by contract type—such as procurement, leasing, employment, and equity transfer. Sample size should be estimated based on the expected improvement and statistical power, not gut feeling.

    Second, set comparison baselines. Include at least: the original base model, an SFT-only version, an SFT+DPO version, and a traditional keyword/rule-based method. Only by comparing against baselines can you attribute improvements to specific steps.

    Third, define labeling guidelines. Have two or more lawyers independently score each review opinion, judging whether risks were identified, whether suggestions are actionable, and whether citations are accurate. Compute Cohen’s Kappa to measure consistency. If Kappa is low, revise the scoring rubric and re-annotate before comparing model results. If only one annotator is available, the report must state this limitation.

    Fourth, set launch thresholds. Before the experiment begins, the team should agree on pass thresholds for key metrics—such as clause recall, risk identification accuracy, and lawyer adoption rate—and confirm them with business stakeholders. Thresholds should not be adjusted after seeing the results.

    When reporting results, always state the test set size, baseline versions, number of annotators, and consistency metrics. Accuracy figures lacking this context should not be used for external promotion.

    7. Pre-Launch Security Checklist

    Before going live, we recommend verifying each of the following:

    • De-identification audit: Sample-check training data, logs, and knowledge bases for residual personal information.
    • Access control and tenant isolation: Data from different firms or clients must be isolated in storage and retrieval, with role-based authentication.
    • Audit logs: Record the requesting user, timestamp, input hash, output, model version, and knowledge base version.
    • Traceable citations: Every review opinion must link back to its source location and knowledge base document.
    • Human review: High-risk or low-confidence opinions must be confirmed by a lawyer; the system must never automatically send review conclusions externally.
    • Prompt injection and privilege protection: Treat contract text as data to be analyzed, not as instructions. If a contract embeds phrases like “ignore the above requirements,” the system should handle them as ordinary text. The model should also never invoke unauthorized tools.
    • Data retention policy: Define how long original contracts and review outputs are stored, with automatic deletion upon expiry.
    • Version management: Keep version records for both the model and the knowledge base so you can roll back to the last stable version when issues arise.