Building a Legal Domain LLM: Technical Architecture and Engineering Practices

    This article explains why general-purpose LLMs underperform on legal tasks and how to build a domain-specific model to address it. It covers base model selection trade-offs, domain-intermediate training, supervised fine-tuning and reinforcement learning, evaluation based on full-task pass rates, integration into document workflows, compliance and safety boundaries, and a phased evolution roadmap.

    The instability of general-purpose LLMs on legal tasks is not primarily caused by insufficient parameter count, but by three structural mismatches.

    The first is a corpus distribution mismatch. Legal statutes, court judgments, contract text, and regulatory Q&A make up a very small share of general pretraining corpora. As a result, models are not sensitive enough to normative modal terms such as “shall,” “may,” and “must not,” and tend to read mandatory clauses as advisory statements.

    The second is a task format mismatch. Legal work does not produce a block of natural language; it produces structured deliverables with precise locations, supporting references, and revision support. Review comments must point to exact clause numbers, and risk conclusions must be traceable to their regulatory sources. This differs markedly from the objective function of general conversational generation.

    The third is a fault-tolerance boundary mismatch. Legal scenarios tolerate hallucination far less than general creative work. A single fabricated article number or a nonexistent precedent can make an entire deliverable unusable.

    Therefore, the focus of building a domain-specific model is not “writing better,” but “locating better, citing better, and refusing to answer when appropriate.”

    2. Technical Approach: From a Lightweight Base to a Domain-Specific Model

    2.1 Engineering Trade-offs in Base Model Selection

    A widely adopted approach in the industry is to choose a lightweight base model rather than an extremely large one. There are three reasons. First, the gains from domain adaptation come mainly from data and training strategy, not from stacking parameters. Second, lightweight base models have low inference costs, making them easy to deploy at scale in the private environments of law firms or corporate legal departments. Third, they have short iteration cycles, so they can be retrained quickly when statutes or regulatory interpretations change.

    2.2 Domain-Intermediate Training

    Intermediate training sits between general pretraining and instruction fine-tuning. Its goal is to continue next-token prediction on large-scale unlabeled or weakly labeled domain corpora, “compressing” domain language patterns into the parameters. Key practices include:

    • Corpus layering: Sample legal normative documents, contract templates, court judgments, and professional textbooks in tiers by quality, avoiding dilution of the signal by low-quality text;
    • Decontamination: Remove text from the same sources as evaluation sets to prevent inflated evaluation results later;
    • Long-context adaptation: Contracts and case files often run to tens of thousands of words, so the context window must be extended during training and position encoding extrapolation must be adapted;
    • Privacy handling: Real case files must undergo subject desensitization and de-identification before entering the training pipeline.

    A skeletal data processing pipeline is shown below (pseudocode, expressing the flow only):

    1. def build_domain_corpus(raw_docs):
    2. docs = [normalize(d) for d in raw_docs] # Unify encoding and structure clauses
    3. docs = [desensitize(d) for d in docs] # Desensitize subject and ID information
    4. docs = [dedup(d) for d in docs] # Collapse near-duplicate documents
    5. docs = [chunk_with_clause_index(d) for d in docs]# Preserve locating anchors such as clause numbers
    6. return [d for d in docs if quality_score(d) > τ]

    2.3 Post-Training: Supervised Fine-Tuning and Reinforcement Learning

    The core of supervised fine-tuning is to turn “general answers” into “deliverable outputs.” Training samples should cover risk point identification, clause rewriting, reference citation, and explicit refusal to answer when evidence is insufficient. Reinforcement learning post-training is used to align preferences. A common practice is to train a reward model on pairwise comparison data annotated by humans or experts, then optimize the policy so that outputs align more closely with expert habits across three dimensions: accuracy, actionability, and citation completeness.

    An aligned review output typically contains four sections:

    1. {
    2. "clause_ref": "Article 8.2",
    3. "risk_level": "High",
    4. "issue": "Unilateral termination right is unequal, with no notice period",
    5. "evidence": "Requirements on contract termination notice in the corresponding regulation",
    6. "suggested_revision": "Both parties have equal termination rights, with 30 days' written notice"
    7. }

    3. Evaluation System: Why Full-Task Pass Rate Matters

    A single accuracy metric can hide real usability. Suppose a contract has 20 risk points and the model identifies 18. Accuracy may look high, but the deliverable still needs manual completion and cannot enter an automated workflow. Industry evaluations therefore usually report two types of metrics together:

    • Full-task pass rate: A task counts as passed only if all sub-items are correct in a single run, measuring end-to-end usability;
    • Fine-grained accuracy: Measures the proportion of correct local judgments, used to locate capability gaps.

    On several public legal evaluation leaderboards, the gap between open-weight models and closed-source models is narrowing. This trend suggests that the contribution of domain data and training strategy can partially replace the advantage of parameter scale. From an engineering perspective, it is advisable to build a small in-house “gold standard set” covering high-frequency contract types and typical dispute points, serving as a regression gate before release.

    4. Deployment Form: Embedding into Real Workflows

    The value of model capability depends on where it appears. Legal professionals mainly work in document editors, so writing capabilities back into documents as revisions and comments is closer to actual practice than providing a standalone chat box.

    A typical integration architecture can be divided into four layers:

    1. Access layer: A desktop or web proxy responsible for identity authentication and permission checks;
    2. Orchestration layer: Document parsing, segmentation, task routing, and tool invocation (retrieving statute and clause libraries);
    3. Model layer: Domain model inference service, combined with retrieval-augmented generation to reduce hallucination;
    4. Write-back layer: Mapping results to document revision records and comment anchors, preserving an interaction in which humans can accept or reject.

    The core of the write-back logic is “anchor alignment,” illustrated below:

    1. def apply_suggestion(doc, suggestion):
    2. anchor = doc.locate_clause(suggestion["clause_ref"])
    3. if anchor is None:
    4. return doc.add_comment(suggestion) # Fall back to a comment if no anchor is located
    5. return doc.tracked_change(anchor, suggestion["suggested_revision"],
    6. comment=suggestion["issue"])

    5. Compliance and Security Boundaries

    Legal data is highly sensitive, so deployment must define clear boundaries: minimize data collection for training and inference, encrypt data in transit and at rest, enforce tenant-level isolation, maintain complete audit logs, and support a configurable no-data-retention policy. A “human-in-the-loop” mechanism should also be retained. Model outputs are positioned as auxiliary opinions rather than legal conclusions, and the responsible party is always the practitioner. For questions beyond the knowledge boundary, the system should explicitly refuse to answer and prompt for supplementary materials rather than forcibly generating a response.

    From an engineering perspective, the evolution of a domain-specific model can proceed in three steps: first add retrieval augmentation to quickly gain traceability, then apply domain-intermediate training to obtain a stable domain language sense, and finally use preference alignment to polish the delivery format. Supporting infrastructure can use a container platform to host inference services, object storage to hold desensitized corpora, a message queue to smooth traffic peaks, and logging services with monitoring and alerting to ensure observability, forming a closed loop for sustainable iteration.