A Practical Guide to Building Domain-Specific LLMs for Legal Work

    This article explains why general-purpose LLMs struggle with legal practice and outlines a three-part approach to building legal domain models: domain continued pre-training, post-training alignment, and workflow integration. It covers corpus strategy, reward design, how to interpret evaluation metrics, a five-step contract review pipeline, deployment and cost considerations, and common risks. The goal is to help developers deliver traceable, evidence-backed legal AI assistance while keeping human review in the loop.

    Legal text differs from general web corpora in three important ways. First, it is dense with long-tail terminology, with extensive cross-references among statutes, judicial interpretations, and contract clauses. Second, it demands a high degree of certainty: a single missed exception clause can change the risk conclusion for an entire contract. Third, outputs must be traceable, with every conclusion pointing back to specific clauses and evidence excerpts.

    General models are trained on internet-scale data. When they encounter expressions such as “apparent authority,” “joint and several liability,” or “valuation adjustment mechanism (VAM) buyback,” they often produce answers that look plausible but miss the substance.

    As a result, the industry has converged on a three-stage approach: domain continued training, post-training alignment, and workflow integration. This is not about rephrasing a general model. It requires changes at three levels simultaneously: data distribution, optimization objectives, and delivery format.

    2. Two Key Stages of Capability Building

    The goal of continued pre-training is not to teach the model to answer questions, but to align its next-token prediction distribution with legal corpora. Key practices include:

    • Corpus mixing: Blend legal source texts, court judgments, contract templates, and regulatory and standards documents in appropriate proportions to avoid overfitting to a single source style.
    • Cleaning and deduplication: Legal text contains many templated, repeated passages. Without deduplication, the model tends to fall into repetitive output.
    • Long-context handling: Contracts and case files can run to tens of thousands of words. Long sequences must be covered during training, not merely concatenated at inference time.

    A simplified illustration of training data organization:

    1. # Illustrative data organization only; not tied to any specific platform API
    2. def build_domain_batch(tokenizer, raw_text, max_len=32768):
    3. ids = tokenizer(raw_text, truncation=True, max_length=max_len)["input_ids"]
    4. return {
    5. "input_ids": ids,
    6. # Continued pre-training typically uses full-sequence language modeling,
    7. # with labels shifted by one position relative to the input
    8. "labels": ids[1:] + [tokenizer.eos_token_id],
    9. }

    2.2 Reinforcement Learning Post-Training: From Writing Fluently to Stating Conclusions with Evidence

    The objective function in post-training differs entirely from intermediate training. The focus is on encoding “useful, evidence-backed, and bounded” into the reward signal. Practical reward dimensions generally fall into three categories:

    • Conclusion correctness: Whether the judgment matches expert-annotated risk assessments.
    • Evidence verifiability: Whether cited clauses can be located at their original positions.
    • Boundary expression: Whether the model explicitly states uncertainty when evidence is insufficient, rather than forcing a conclusion.

    In engineering practice, a hybrid scoring scheme is common: rule-based checks, model review, and human spot checks. This avoids a single reward model being fooled by persuasive phrasing.

    3. How to Read Evaluation Scores

    Legal model evaluations commonly use two measures, and many misreadings come from confusing them:

    • Task pass rate: A task counts as passed only if all of its sub-judgments are correct. This is a strict measure, so the numbers are naturally low.
    • Overall accuracy: The proportion of correct individual judgments. This number is higher, but still a distance away from “ready for direct delivery.”

    So a result such as “roughly 20% pass rate and about 85% accuracy” should be read as follows: the model is usable for single-point judgments, but multi-step chained tasks still require human review. Treating high accuracy as equivalent to “unattended operation” is the most common source of incidents during deployment.

    4. Embedding into Real Workflows: A Contract Review Example

    Evaluation scores only matter inside a workflow. A reusable contract review pipeline typically has five steps:

    1. Parse: Restore clause hierarchy, tables, and attachments, preserving paragraph numbering.
    2. Retrieve: Locate applicable regulations and internal review rules.
    3. Judge: Assign a risk level and reasoning to each clause.
    4. Present: Write changes back into the document as revisions and comments, rather than producing a separate report.
    5. Review: Archive after human confirmation, and feed corrected samples back as training data.

    Illustrative output structure:

    1. {
    2. "clause_id": "3.2",
    3. "risk": "high",
    4. "reason": "No cap on liability for breach, and no exclusion of indirect losses",
    5. "evidence": [{"loc": "Clause 3.2", "quote": "..."}],
    6. "suggestion": "Add a liability cap and a definition of loss scope"
    7. }

    Step 4 is the dividing line for user experience. Legal professionals work in the document itself. If the model can only output chat-style conclusions, humans still have to transfer them manually, which cancels out the efficiency gains. Therefore, the ability to make in-place revisions and comments within the document often determines adoption more than leaderboard rankings.

    5. Deployment and Cost: Prefer Lightweight Base Models

    Legal workloads are typically concentrated on long documents and low-frequency, high-value tasks. This makes model selection the opposite of general high-concurrency scenarios: long-context stability, cost per document, and private deployment feasibility matter more than peak throughput. A lightweight base model combined with domain training offers a better balance between quality and inference cost.

    When running on general cloud capabilities, a common combination is: object storage for original case files, a message queue to decouple long-running tasks, a container platform to host inference services, and logging plus monitoring and alerting services for quality observation. Sensitive data should preferably go through private deployment or a dedicated network, with masking and access auditing in place.

    6. Common Risks and How to Avoid Them

    • Data compliance: Training and inference corpora need clear authorization boundaries, and personal information should be masked.
    • Hallucination and overconfidence: Enforce an evidence field, and output uncertainty when no evidence is available.
    • Evaluation contamination: Keep internal rule sets isolated from public evaluation sets to avoid inflated scores.
    • Responsibility boundaries: Position model output as “assisted review opinions”; final signing responsibility always remains with humans.

    7. Conclusion

    The value of legal domain models lies not in replacing legal judgment, but in compressing repetitive, error-prone, time-consuming comparison work to an acceptable cost. For developers, the pragmatic path is to build a foundation with domain intermediate training, align delivery standards through post-training, complete the last mile with in-document revisions and comments, and protect the quality baseline with strict evaluation measures and human review. Baidu AI Cloud, with capabilities in general model services and document intelligence, can serve as one infrastructure option for carrying such workflows.